如何把質數後面加逗號,
並且每10個質數換行,
還有全部質數加起來有幾個。
幫修改拜託哩~~
import java.util.*;
public class Prime {
public static int[] findPrimes(final int max) {
int[] prime = new int[max+1];
ArrayList list = new ArrayList();
for(int i = 2; i <= max; i++)
prime[i] = 1;
for(int i = 2; i*i <= max; i++) { // 這邊可以改進
if(prime[i] == 1) {
for(int j = 2*i; j <= max; j++) {
if(j % i == 0)
prime[j] = 0;
}
}
}
for(int i = 2; i < max; i++) {
if(prime[i] == 1) {
list.add(new Integer(i));
}
}
int[] p = new int[list.size()];
Object[] objs = list.toArray();
for(int i = 0; i < p.length; i++) {
p[i] = ((Integer) objs[i]).intValue();
}
return p;
}
public static void main(String[] args) {
int[] prime = Prime.findPrimes(100);
int sum = 0;
for(int i = 0; i < prime.length; i++) {
System.out.print(\\nprime[i] + " ");
sum = sum + prime[i];
}
System.out.println("\\n總和:" + sum);
}
}
2006-10-10 13:57:16 · 2 個解答 · 發問者 Dennis小築 1 in 電腦與網際網路 ➔ 程式設計
你的 findPrimes 方法寫得不錯,不需要再改了。所以我僅就你想要的 10 個質數換行以及印出總個數來更改 main 方法,請參考我的寫法。 public static void main(String[] args) { int[] prime = Prime.findPrimes(100); int sum = 0; int flag = 1; for(int i = 0; i < prime.length; i++, flag++) { if (flag == 1) { System.out.print("" + prime[i]); } else if (flag <= 9) { System.out.print(", " + prime[i]); } else { flag = 0; System.out.println(", " + prime[i]); } sum = sum + prime[i]; } System.out.println(); System.out.println("總和:" + sum); System.out.println("個數: " + prime.length); }
2006-10-10 17:23:01 · answer #1 · answered by ? 7 · 0⤊ 0⤋
那是...抄良葛格網站的吧?
2006-10-10 18:17:06 · answer #2 · answered by ? 6 · 0⤊ 0⤋