// control/Primes.java
// TIJ4 Chapter Control, Exercise 4, page 139
// Write a program that uses two nested for loops and the modulus operator (%)
// to detect and print prime numbers.
public class Primes {
public static void main(String[] args) {
for(int i = 1; i < 1000; i++ ) {
int factors = 0;
for(int j = 1; j < (i + 2)/2; j++ ) {
if((i % j) == 0) factors++;
}
if(factors < 2) System.out.println(i + " is prime");
}
}
}
首先素数就是不能被其他整数整除吧,那么要判断一个数i是不是素数,就让i去除以所有比它小的整数。其实不用除以所有比它小的,比如有i=m*n,那么肯定有i=n*m,所以不管m,n大小如何,只要i除以较小的一个就好,所以只用循环至i的一半,就是i/2,所以有j<(i/2+1)