【发布时间】:2014-04-28 13:28:30
【问题描述】:
所以我写了这段代码,我很自豪,因为我很长时间没有写代码了。它的作用是询问一个数字,然后打印从 1 到该数字的所有质数。
import java.util.Scanner;
class PrimeNumberExample {
public static void main(String args[]) {
//get input till which prime number to be printed
System.out.println("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
//printing primer numbers till the limit ( 1 to 100)
System.out.println("Printing prime number from 1 to " + limit);
for(int number = 2; number<=limit; number++){
//print prime numbers only
if(isPrime(number)){
System.out.println(number);
}
}
}
/*
* Prime number is not divisible by any number other than 1 and itself
* @return true if number is prime
*/
public static boolean isPrime(int number){
for(int i=2; i<number; i++){
if(number%i == 0){
return false; //number is divisible so its not prime
}
}
return true; //number is prime now
}
}
但是,我想要它做的是要一个数字,让我们取 10,然后打印前 10 个素数,我试图看看是否能找到方法,但我不知道如何因为我没有那么多使用java。我希望你能并且会帮助我。
【问题讨论】:
-
所以你可以做到这一点,但不能做其他任务?嗯...
-
只是因为这个问题是关于生成素数的,也许看看Sieve of Eratosthenes
-
您必须使用计数来停止生成素数,而不是使用循环索引。在下面检查我的代码... :)