注意兩點:① 什么是素數?② 如何利用計算機的方法去解決問題?
public static void NumberDemo(){ int x = 0; System.out.println("3~100之間的所有素數:"); for(int i=3; i<100;i++){//外層循環 int n= (int)Math.sqrt(i); boolean flag = true; for(int j=2; j<=n; j++){//內層循環 if (i%j == 0) { flag = false; } } if (flag) { System.out.print(i + " "); x++; if (x%5 == 0) { System.out.println();//控制每行打印5個素數 } } } }
結果展示: