[英]prime numbers between 1 and 100 in java
伙計們,我一直在試圖弄清楚為什么這段代碼在將近 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);
}
}
}
您的代碼應該具有嵌套循環和一個數組,該數組存儲要在最后顯示的素數。
要在最后打印它們,您應該首先打印您的語句,然后使用循環打印包含找到的素數的數組。
如果你想打印從 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)
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+", ");
}
}}
我要感謝大家的建議和提示。 以及推動我的動力。 我能夠讓程序運行。 見下文
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++;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.