伙计们,我一直在努力弄清楚为什么这段代码将近5个小时都没有显示出适当的结果!这应该是一个非常容易的任务,但它使我发疯。我必须使该项目能够使用包含的代码而不是其他类似的代码。 我的问题是没有在软件底部显示质数。根据我的理解,此代码应显示质数1-100,并且所有数均由5个数字组成,最后一个数字除外。 一些指导非常感谢。
public class Prime numbers 1-100{
public static void main (String[] args) {
int number = 100;
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test if number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
break; // Exit for loop
}
// print prime numbers
if(isPrime)
System.out.println("Prime numbers between 1 and " + number);
}
}
}
答案 0 :(得分:0)
您的代码应具有嵌套循环和一个数组,该数组存储找到的质数显示在末尾。
要在最后打印它们,您应该先打印您的语句,然后使用循环来打印包含找到的素数的数组。
答案 1 :(得分:0)
如果要打印从1到100的所有质数,则必须遍历所有这些数字(第一个循环),并且对于每个质数都遍历所有可能的除数(嵌套循环):
>
int number = 100;
boolean isPrime = false;
System.out.println("2");
System.out.println("3");
for (int i = 5; i <= number; i++) {
for (int divisor = 2; divisor <= Math.sqrt(i); divisor++) {
isPrime = !(i % divisor == 0);
if (!isPrime)
break;
}
if (isPrime)
System.out.println("" + i);
}
注意,对于2和3条件无法应用,因此先打印它们。
我使用了@selbie的优化提示<= sqrt(number)
答案 2 :(得分:-1)
public class Prime{
public static void main (String[] args) {
boolean isPrime = true;
// iterate over all numbers from 1 to 100
for (int number = 1; number <= 100; number++) {
// We want to believe it's a prime
isPrime = true;
// 1 is not a prime
if (number == 1) isPrime = false;
// iterate over all numbers which are lower then 'number'
for (int divisor = 2; divisor < number && isPrime; divisor++) {
// if we can divide by it, it's not a prime
if (number % divisor == 0) {
isPrime = false;
}
}
// print if it's a prime
if (isPrime) System.out.println(number+", ");
}
}}
答案 3 :(得分:-1)
我要感谢大家的建议和技巧。和推动我的动力。我能够使该程序正常工作。见下文
public class primes {
public static void main (String[] args) {
final int NUMBER_OF_PRIMES = 26; // Number of primes to display
final int NUMBER_OF_PRIMES_PER_LINE = 5; // Display 5 numbers per line
int count = 0; // Count the number of prime numbers
int number = 1; // A number to be tested for primeness
System.out.println("The prime numbers between 1 and 100 are \n");
// Repeatedly find prime numbers
while (count < NUMBER_OF_PRIMES) {
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
// Test whether number is prime
for (int divisor = 2; divisor <= number / 2; divisor++) {
if (number % divisor == 0) { // If true, number is not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
}
// Display the prime number and increase the count
if (isPrime) {
count++; // Increase the count
if (count % NUMBER_OF_PRIMES_PER_LINE == 0) {
// Display the number and advance to the new line
System.out.println(number);
}
else
System.out.print(number + " ");
}
//Check if the next number is prime
number++;
}
}
}