使用Java撰寫一支可印出小於n的所有質數的方法。
重點是要先理解什麼是質數,其實只要理解什麼是質數後問題就簡單多了。質數(Prime Number)是指不能被自己和1整除且大於1的自然數,例如2, 3, 5, 7, 9, 11, 13, ...,如果能被其他的數整除則不是質數
public class Prime {
public static void main(String[] args){
printPrime(2);
}
public static void printPrime(int n){
if(n <= 1) {
System.out.println("n要大於1");
return;
}
StringBuilder primes = new StringBuilder();
for (int dividend = 2; dividend < n; dividend++){
int dividedCount = 0; // 被1和本身以外的數整除的次數
for(int divisor = (dividend - 1); divisor > 1; divisor--){
if(dividend % divisor == 0) {
dividedCount++;
}
}
if(isPrime(dividedCount)) {
primes.append(dividend).append(",");
}
}
if(primes != null && primes.length() > 0){
primes = primes.delete(primes.length() - 1, primes.length());
}
System.out.println(primes.toString());
}
private static boolean isPrime(int dividedCount){
return dividedCount == 0 ? true : false;
}
}
參考:
You have explained prime number generation program very well with appropriate explanation. Thanks for sharing.
回覆刪除Cheers,
http://www.flowerbrackets.com/java-program-to-find-prime-number/