我正在尝试编写一些代码,这些代码占用了最大数量,并且给了我所有2和最大数字之间的素数。它几乎正常工作,但我遇到打印所有素数的问题,但它也会打印相同素数的结果。例如,它将打印2,3,4,5,7,9,它们都是介于0和10之间的素数,但它也会打印额外的数字,即2 * 2,3 * 3,依此类推。请指导我正确的方向,以便我完成这个计划。
public class PrimeNumbers
{
public static void main( String[] args )
{
int max = 400;
//Runs through all the numbers between 2 and max, checks if
//the number is prime and prints it
for( int num = 2; num < max; ++num )
{
if( isPrimeNumber( num ) )
{
System.out.println( num );
}
}
}
//method to find all prime numbers
public static boolean isPrimeNumber( int number )
{
for( int mod = 2; mod < Math.sqrt( number ); ++mod )
{
if( number % mod == 0 )
{
return false;
}
}
return true;
}
}
答案 0 :(得分:5)
你的最终条件是错误的,你需要一直到sqrt(num)
:
for (int mod = 2; mod <= Math.sqrt(number); ++mod)
答案 1 :(得分:0)
对于将来的用户,我将发布此程序以作准备。您只需提供希望质数返回的最大数字即可。
import java.util.Scanner;
public class prim {
public static void main(String[] args) {
int x = 2;
int y = 2;
int i = 0;
int m = 0;
int t = 1;
int j = 2;
int cal = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("please enter for how many numbers \nyou wanna check if their prime");
m = keyboard.nextInt();
for (i = 0; i <= m; i++) {
while (j <= x) {
t = x % y;
if (t == 0) {
cal = cal + 1;
}
y++;
j++;
}
if (cal == 1) {
System.out.println("Prime number: " + x);
}
cal = 0;
x++;
y = 2;
j = 2;
}
}
}