📌  相关文章
📜  [L,R]范围内的(2 ^ x * 3 ^ y)形式的整数计数

📅  最后修改于: 2021-05-04 09:50:55             🧑  作者: Mango

给定范围[L,R] ,其中0≤L≤R≤10 8 。任务是从给定范围内找到可以表示为(2 x )*(3 y )的整数计数。

例子:

方法:由于数字是2和3的幂,所以会快速增长,因此可以使用以下算法。对于[1,10 8 ]范围内(2 x )*(3 y )形式的所有数字,请将它们存储在向量中。稍后对向量进行排序。然后,可以使用上限来计算所需答案。当存在许多形式为[L,R]的查询时,预先计算这些整数将很有帮助。

下面是上述方法的实现:

// C++ implementation of the approach
#include 
using namespace std;
  
#define MAXI (int)(1e8)
  
// To store all valid integers
vector v;
  
// Function to find all the integers of the
// form (2^x * 3^y) in the range [0, 1000000]
void precompute()
{
  
    // To store powers of 2 and 3
    // initialized to 2^0 and 3^0
    int x = 1, y = 1;
  
    // While current power of 2
    // is within the range
    while (x <= MAXI) {
  
        // While number is within the range
        while (x * y <= MAXI) {
  
            // Add the number to the vector
            v.push_back(x * y);
  
            // Next power of 3
            y *= 3;
        }
  
        // Next power of 2
        x *= 2;
  
        // Reset to 3^0
        y = 1;
    }
  
    // Sort the vector
    sort(v.begin(), v.end());
}
  
// Function to find the count of numbers
// in the range [l, r] which are
// of the form (2^x * 3^y)
void countNum(int l, int r)
{
    cout << upper_bound(v.begin(), v.end(), r)
                - upper_bound(v.begin(), v.end(), l - 1);
}
  
// Driver code
int main()
{
    int l = 100, r = 200;
  
    // Pre-compute all the valid numbers
    precompute();
  
    countNum(l, r);
  
    return 0;
}
输出:
5