您的位置:首页 > 编程语言 > Java开发

求素数(Thinking in Java 4th Edition)

2011-11-14 14:40 387 查看
读到了Thinking in Java 4th Editon的第四章,遇到了求素数算法,记录一下。

Write a program to detect and print prime numbers (Integers evenly divisible only by themselves and 1), using two nested for loops and the modulus operator (%).

package control;

public class E04_FindPrimes {
public static void main(String[] args) {
int max = 100;
// Get the max value from the command line,
// if the argument has been provided:
if (args.length != 0) {
max = Integer.parseInt(args[0]);
}

for (int i = 1; i < max; i++) {
boolean prime = true;

for (int j = 2; j < i; j++) {
if (i % j == 0) {
prime = false;
}
}

if (prime) {
System.out.print(i + " ");
}
}
}
}


1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: