日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java黑皮书课后题第5章:*5.20(打印2到1000之间的素数)修改程序清单5-15,打印2到1000之间(包括2和1000)的所有素数。每1行显示8个素数,数字之间用一个空格字符隔开

發(fā)布時間:2024/7/23 java 38 豆豆

*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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。