Java黑皮书课后题第5章:*5.20(打印2到1000之间的素数)修改程序清单5-15,打印2到1000之间(包括2和1000)的所有素数。每1行显示8个素数,数字之间用一个空格字符隔开
生活随笔
收集整理的這篇文章主要介紹了
Java黑皮书课后题第5章:*5.20(打印2到1000之间的素数)修改程序清单5-15,打印2到1000之间(包括2和1000)的所有素数。每1行显示8个素数,数字之间用一个空格字符隔开
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
*5.20(打印2到1000之間的素數(shù))修改程序清單5-15,打印2到1000之間(包括2和1000)的所有素數(shù)。每1行顯示8個素數(shù),數(shù)字之間用一個空格字符隔開
- 題目
- 題目概述
- 程序清單5-15(非本題代碼)
- 破題
- 代碼
題目
題目概述
*5.20(打印2到1000之間的素數(shù))修改程序清單5-15,打印2到1000之間(包括2和1000)的所有素數(shù)。每1行顯示8個素數(shù),數(shù)字之間用一個空格字符隔開
程序清單5-15(非本題代碼)
public class qingdan {public static void main(String[] args) {// Number of primes to display:輸出50個素數(shù)final int NUMBER_OF_PRIMES = 50;// Display 10 per line:一行10個數(shù)字final int NUMBER_OF_PER_LINE = 10;// Count the number of prime numbers:計數(shù)變量int count = 0;// A number to be tested for primeness:測試用變量int number = 2;System.out.println("The first 50 prime numbers are \n");// Repeatedly find prime numberswhile (count < NUMBER_OF_PRIMES) {// Assume the number is primeboolean isPrime = true; // Is the current number prime?// Test whether number is primefor(int divisor = 2; divisor <= number / 2;divisor++){if (number % divisor == 0){ // If true, number is not primeisPrime =false;break;}}// Display the prime number and increase the countif( isPrime ){count++; // Increase the countif(count % NUMBER_OF_PER_LINE == 0){// Display the number and advance to the new lineSystem.out.println(number);}elseSystem.out.print(number + " ");}// Check if the next number is primenumber++;}} }破題
程序清單5-15其實不用改多少部分,計算素數(shù)的代碼已近給出了,只需要修改前后參數(shù)即可
代碼
public class Test5_20 {public static void main(String[] args) {// Number of primes to display:輸出50個素數(shù)//final int NUMBER_OF_PRIMES = 50;// Display 10 per line:一行10個數(shù)字final int NUMBER_OF_PER_LINE = 10;// Count the number of prime numbers:計數(shù)變量int count = 0;// A number to be tested for primeness:測試用變量//int number = 2;System.out.println("2~1000之間的素數(shù)有: \n");// Assume the number is primeboolean isPrime = false; // Is the current number prime?// Repeatedly find prime numbersfor(int number = 2;number <= 1000; number++){for(int test = 2; test <= (number / 2);test++){if( number % test == 0){isPrime = true;++count; // Increase the count}// Display the prime number and increase the countif(isPrime){isPrime = false;if(count % NUMBER_OF_PER_LINE == 0){// Display the number and advance to the new lineSystem.out.println(number);}elseSystem.out.print(number + " ");break;}// Check if the next number is prime//number++;}}} } 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的Java黑皮书课后题第5章:*5.20(打印2到1000之间的素数)修改程序清单5-15,打印2到1000之间(包括2和1000)的所有素数。每1行显示8个素数,数字之间用一个空格字符隔开的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java黑皮书课后题第5章:**5.19
- 下一篇: Java黑皮书课后题第5章:**5.21