在Java中显示下N个质数的代码。

huangapple go评论79阅读模式
英文:

To display next N numbers of prime numbers in java

问题

我想在Java中显示下n个素数的数字

所以我接受了来自用户的两个输入

他输入一个数字,然后输入要打印的下一个素数的数量

但是我没有得到任何输出,也没有任何错误

我创建了一个isprime()函数,如果数字是素数,则返回true,否则返回false
然后在main()函数中,我创建了一个count变量来显示要打印多少个数字

import java.util.Scanner;
class NprimeNumbers 
{
    public static boolean isprime(int num)
    {
        int count=0;

        int i;
        for(i=1;i<=num;i++)
        {
            if(num%i==0)
            {
                count++;
            }
        }
        if(count==2)
            return true;
        else
            return false;
    }
    public static void main(String[] args)
    {

        Scanner sc=new Scanner(System.in);

        System.out.println();

        System.out.print("Enter the number : ");
        int number=sc.nextInt();

        System.out.print("How many prime numbers to print : ");
        int hmw=sc.nextInt();

        System.out.println();

        System.out.println("------------------------------OUTPUT------------------------------");

        System.out.println();

        int count=0;           
        
        if(isprime(number))
        {
            while(count==hmw)
            {
                System.out.print(number+",");
            }
            count++;
            number++;
        }
    }  
}

输出应该是 13,17,19,23,27

英文:

I want to display next n numbers of prime numbers in java

so what i did is accepting the two inputs from user

he enters one number and then he enters the how many next prime numbers to be printed

but i am not getting any output there is no any error

i have created a isprime() which returns true or false if number is prime or not
and then in main() i created count variable to display howmany numbers to be printed

import java.util.Scanner;
class NprimeNumbers 
{
public static boolean isprime(int num)
{
int count=0;
int i;
for(i=1;i&lt;=num;i++)
{
if(num%i==0)
{
count++;
}
}
if(count==2)
return true;
else
return false;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println();
System.out.print(&quot;Enter the number : &quot;);
int number=sc.nextInt();
System.out.print(&quot;How many prime numbers to print : &quot;);
int hmw=sc.nextInt();
System.out.println();
System.out.println(&quot;------------------------------OUTPUT------------------------------&quot;);
System.out.println();
int count=0;           
if(isprime(number))
{
while(count==hmw)
{
System.out.print(number+&quot;,&quot;);
}
count++;
number++;
}
}
}

在Java中显示下N个质数的代码。

The output should be 13,17,19,23,27

答案1

得分: 1

以下是翻译好的部分:

'while'循环应该位于'if'语句外部,因为您希望它一直运行,直到找到下一个5个素数。只有当'isprime()'返回true时,您才希望输出数字并增加'count'。'number'变量应在'if'语句外部增加,因为我们需要下一个数字,无论当前的数字是否为素数。
因此,它应该看起来更像这样:
number++; // 跳过输入的数字
int count=0;
while (count < hmw) {
if(isprime(number))
{
System.out.print(number+",");
count++;
}
number++;
}
如上所述,您的'isprime()'函数效率非常低下。稍微修复的方法是从2开始,直到num-1停止,一旦其中一个数字均匀地分割候选数字,立即返回false,因为在那个点之后没有继续检查更多的数字是没有必要的。只有在确定没有数字均匀地分割候选数字之后才返回true:
public static boolean isprime(int num)
{
for(int i=2;i<num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}
如果您再进一步,我们可以通过使用候选数字的平方根来减少检查的次数,如“试除法”部分所述,将其作为for循环的上限:
public static boolean isprime(int num)
{
int upperBound = (int)Math.sqrt((double)num);
for(int i=2;i<=upperBound;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}

请注意,这些翻译是您提供的代码的中文翻译部分,不包含问题的回答。

英文:

The while loop should be on the outside of the if statement as you want it to run until the next 5 primes have been found. You only want to output the number and increase count if isprime() returns true. The number variable should be increased outside of the if statement since we need the next number regardless if the current one was a prime or not.

So it needs to look more like:

number++; // skip the number they entered
int count=0;                   
while (count &lt; hmw) {
if(isprime(number))
{
System.out.print(number+&quot;,&quot;);  
count++;                        
}
number++;
}

As mentioned, your isprime() function is really inefficient. A slight fix would be to start at 2 and stop at num-1, returning false as soon as one of the numbers evenly divides into the candidate, as there's no reason to check any more numbers past that point. Only return true after you've determined that no numbers evenly divide into the candidate:

public static boolean isprime(int num)
{
for(int i=2;i&lt;num;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}

If you go a step further, we can reduce the number of checks by using the square root of the candidate number, as described in the trial division section, as the upper bound of the for loop:

public static boolean isprime(int num)
{
int upperBound = (int)Math.sqrt((double)num);
for(int i=2;i&lt;=upperBound;i++)
{
if(num%i==0)
{
return false;
}
}
return true;
}

答案2

得分: 1

你的问题在于 while 循环的结构和条件。你的条件是 count==hmw。这意味着只有当要打印的素数数量为 0 时(因为你手动将 count 设置为 0),才会执行 while 循环。你需要将它改为 count <= hmw(你也可以将其改为 count != hmw,但 <= 更好,因为如果 count 不小心超过了 hmw,你仍然安全。

此外,你的 while 循环的增量也有一些问题。你在循环外面进行增量操作:

while(count==hmw)
{
System.out.print(number+&quot;,&quot;);
}
count++;
number++;

你需要将增量操作放在循环内部:

while(count!=hmw)
{
System.out.print(number+&quot;,&quot;);
count++;
number++;
}

现在这应该是你的输出:

输入数字:3
要打印多少个素数:4

------------------------------输出------------------------------

3,4,5,6,
进程以退出代码 0 结束

然而,如果你想要在用户输入数字后才打印素数,你需要将条件语句放在 while 循环内部:

while(count<=hmw)
{
if(isprime(number)) {
System.out.print(number + &quot;,&quot;);
count++;
}
number++;
}

现在你的输出完美,如下所示:

输入数字:3
要打印多少个素数:4

------------------------------输出------------------------------

3,5,7,11,13,
进程以退出代码 0 结束

希望这有所帮助!

英文:

You problem is the structure and the condition of your while loop. Your condition is count==hmw. This is saying to execute the while loop only if the number of prime numbers they want to print is 0 (because you manually set count to 0). You need to make it count &lt;= hmw (you could make it count != hmw but &lt;= is better because if count somehow goes past hmw you are safe.

The incrementing of your while loop also has some issues. You increment outside the while loop with:

while(count==hmw)
{
System.out.print(number+&quot;,&quot;);
}
count++;
number++;

You need to put the increments inside the loop:

while(count!=hmw)
{
System.out.print(number+&quot;,&quot;);
count++;
number++;
}

Now this should be your output:

Enter the number : 3
How many prime numbers to print: 4

------------------------------OUTPUT------------------------------

3,4,5,6,
Process finished with exit code 0

However, if you want to print prime numbers only after the number is input by the user, you need to put your conditional statement in your while loop:

while(count&lt;=hmw)
{
if(isprime(number)) {
System.out.print(number + &quot;,&quot;);
count++;
}
number++;
}

Now your output is perfect and looks like this:

Enter the number : 3
How many prime numbers to print: 4

------------------------------OUTPUT------------------------------

3,5,7,11,13,
Process finished with exit code 0

Hope this Helps!

答案3

得分: 1

您可以使用迭代的 for-loop 来循环 hwm 次。

for-loop 中,使用 while-loop 来检查 isprimenumber

需要注意的是,在这种情况下,while-loop 不需要任何封闭的代码块,因为我们将在 isprime 调用中增加 number
O'Reilly Media – Java, A Beginner's Guide, 5th Edition – "Loops with no Body"

for (int count = 1; count &lt;= hmw; count++) {
    while (!isprime(++number));
    System.out.print(number+",");
}

以下是输入和输出。

输入数字:11
要打印多少个素数:5
------------------------------输出------------------------------
13,17,19,23,29,
英文:

You can use an iterative for-loop to loop hwm times.

Within the for-loop, use a while-loop to check isprime with number.

As a note, in this case, the while-loop doesn't require any enclosing code block, since we'll increase number within the isprime call.
O'Reilly Media &ndash; Java, A Beginner's Guide, 5th Edition &ndash; "Loops with no Body".

for (int count = 1; count &lt;= hmw; count++) {
    while (!isprime(++number));
    System.out.print(number+&quot;,&quot;);
}

Here is the input and output.

Enter the number : 11
How many prime numbers to print : 5
------------------------------OUTPUT------------------------------
13,17,19,23,29,

答案4

得分: 0

这是您提供的Java代码的中文翻译:

import java.util.Scanner;

class NprimeNumbers {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.print("输入数字:");
        int currentNumber = scan.nextInt();

        System.out.print("要打印多少个素数:");
        int n = scan.nextInt();

        printNPrimes(currentNumber, n);

        scan.close();
    }

    public static boolean isprime(int num) {
        for (int divisor = 2; divisor <= Math.sqrt(num); ++divisor) {
            if (num % divisor == 0) {
                return false;
            }
        }
        return true;
    }

    public static void printNPrimes(int currentNumber, int n) {
        int nextPrime = currentNumber + 1;
        while (n > 0) {
            if (isprime(nextPrime)) {
                System.out.print(nextPrime + " ");
                --n;
                ++nextPrime;
            } else {
                ++nextPrime;
            }
        }
        System.out.println();
    }
}

只提供代码的翻译,没有其他内容。

英文:
import java.util.Scanner;
class NprimeNumbers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print(&quot;Enter the number : &quot;);
int currentNumber = scan.nextInt();
System.out.print(&quot;How many prime numbers to print : &quot;);
int n = scan.nextInt();
printNPrimes(currentNumber, n);
scan.close();
}
public static boolean isprime(int num) {
for (int divisor = 2; divisor &lt;= Math.sqrt(num); ++divisor) {
if (num % divisor == 0) {
return false;
}
}
return true;
}
public static void printNPrimes(int currentNumber, int n) {
int nextPrime = currentNumber + 1; // 12
while (n &gt; 0) {
if (isprime(nextPrime)) {
System.out.print(nextPrime + &quot; &quot;);
--n;
++nextPrime;
} else {
++nextPrime;
}
}
System.out.println();
}
}

huangapple
  • 本文由 发表于 2023年6月8日 23:12:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76433329.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定