简体   繁体   English

给定数字n,我们必须找出小于或等于n的正好有3个除数的数字

[英]given a number n , we have to find out such numbers that are less than or equal to n, that have exactly 3 divisors

i have used sieve of eratosthenes method to calculate such numbers that have exactly 3 divisors and are less than or equal to n where n is the given number. 我已经使用过擦除数筛法来计算具有正好3个除数并且小于或等于n的数字,其中n是给定的数字。

the problem with this code is that it give answer 37386 for n=999999,but the correct answer is 168 此代码的问题是它给出n = 999999的答案37386,但正确的答案是168

public static void main (String[] args) throws java.lang.Exception
{
    Scanner scn =new Scanner(System .in);
    print("enter the prime no");
    int n= scn.nextint();
    int arr[]= new int[n+1];
    for(int i=2;i<arr.length;i++)
    {
        arr[i]=1;
    }

    for(int i=2;i*i<=n;i++)
    {
        if(arr[i]==1)
        {

            for(int p=2;p*i<=n;p++)
            {
                arr[p*i]=0;
            }
        }
    }

    int count=0;
    for(int i=2;i<=n;i++)
    {
        if(arr[i]==1&&i*i<n)
        {
            count++;
        }
    }

    System.out.print(count);
}

code for calculating numbers that have exactly 3 divisors 计算正好具有3个除数的数字的代码

The Sieve of Eratosthenes is used to calculate prime numbers. Eratosthenes的筛子用于计算素数。 Your code correctly calculates that there are 37386 prime numbers less than 999999. It should be possible to modify the code to find numbers with exactly three divisors rather than one, but I will leave that as an exercise to the asker. 您的代码正确地计算出有少于379999个质数的37386个质数。应该可以修改该代码以找到正好具有三个除数而不是一个除数的数字,但是我将其作为练习者进行询问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM