請問 …
如何用『while迴圈』寫一個判斷質數&共有幾個的java程式呢?
2007-01-01 20:52:28 · 3 個解答 · 發問者 littlechang 1 in 電腦與網際網路 ➔ 程式設計
請參考我的做法。
import java.io.*;
public class PrimeTest {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("請輸入一個正整數:");
int x = Integer.parseInt(br.readLine());
boolean isPrime = true;
for (int i = 2; i <= x/2; i++) {
if (x % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) System.out.println(x + " 為質數");
else System.out.println(x + " 不為質數");
}
}
2007-01-02 09:36:37 · answer #1 · answered by ? 7 · 0⤊ 0⤋
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
System.out.println("請輸入一整數:");
int n = kbd.nextInt();
int count = 2, check;
boolean isPrime;
while(count <= n)
{
isPrime = true;
check = 2;
while(check < n)
{
if((count%check==0)&&(count!=check))
{
isPrime = false;
break;
}
check++;
}
if(isPrime)
System.out.print(count+" ");
count++;
}
}
您也可以參考
http://tw.knowledge.yahoo.com/question/question?qid=1606122602930
希望這樣有幫到你
豚仔
2007-01-02 03:42:56 · answer #2 · answered by 安迪豬 6 · 0⤊ 0⤋
http://tw.knowledge.yahoo.com/question/question?qid=1206050609854
http://tw.knowledge.yahoo.com/question/question?qid=1106120500556
2007-01-02 02:02:34 · answer #3 · answered by ? 4 · 0⤊ 0⤋