📜  计算不超过N的整数,该整数等于任何大于1的整数的至少2次幂

📅  最后修改于: 2021-04-17 17:54:38             🧑  作者: Mango

给定正整数N ,任务是计算范围为[1,N]的整数数,该整数可以表示为a b ,其中ab是大于1的整数。

例子:

方法:给定问题可以通过计算所有可能的元素对(a,b)来解决,使得a b最多为N。请按照以下步骤解决问题:

  • 初始化一个HashSet来存储b的所有可能值,最多为N。
  • 遍历范围[2,1√N],并为每一个值,至多N,插入一个具有B值的所有可能值,其中b位于在范围[1,N]。
  • 完成上述步骤后,将HashSet的大小打印为整数的结果计数。

下面是上述方法的实现:

Java
// Java program for the above approach
 
import java.util.HashSet;
 
public class GFG {
 
    // Function to count the integers
    // up to N that can be represented
    // as a ^ b, where a &b > 1
    static void printNumberOfPairs(int N)
    {
        // Initialize a HashSet
        HashSet st
            = new HashSet();
 
        // Iterating over the range
        // [2, sqrt(N)]
        for (int i = 2; i * i <= N; i++) {
 
            int x = i;
 
            // Generate all possible
            // power of x
            while (x <= N) {
 
                // Multiply x by i
                x *= i;
 
                // If the generated number
                // lies in the range [1, N]
                // then insert it in HashSet
                if (x <= N) {
                    st.add(x);
                }
            }
        }
 
        // Print the total count
        System.out.println(st.size());
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int N = 10000;
        printNumberOfPairs(N);
    }
}


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to count the integers
// up to N that can be represented
// as a ^ b, where a &b > 1
static void printNumberOfPairs(int N)
{
     
    // Initialize a HashSet
    HashSet st = new HashSet();
 
    // Iterating over the range
    // [2, sqrt(N)]
    for(int i = 2; i * i <= N; i++)
    {
        int x = i;
 
        // Generate all possible
        // power of x
        while (x <= N)
        {
             
            // Multiply x by i
            x *= i;
 
            // If the generated number
            // lies in the range [1, N]
            // then insert it in HashSet
            if (x <= N)
            {
                st.Add(x);
            }
        }
    }
 
    // Print the total count
    Console.WriteLine(st.Count);
}
 
// Driver Code
public static void Main(string[] args)
{
    int N = 10000;
    printNumberOfPairs(N);
}
}
 
// This code is contributed by ukasp


输出:
124

时间复杂度: O(N log N)
辅助空间: O(N)