public class All {
public static void main(String[] args) {
int a[] = new int[200];
//將前200個數中的素數提取出來放入數組a中
for(int i = 1 ; i < 200 ; i ++){
boolean isPrime = true;
for(int k = 2 ; k < i ; k ++){
if( i % k == 0){
isPrime = false;
break ;
}
}
if(isPrime){
a[i-1] = i;
System.out.println(a[i-1]); //打印確認
}
}
// 輸入兩個數 m,n 求第m個素數到底n個素數之間的素數和
Scanner small = new Scanner(System.in);
Scanner large = new Scanner(System.in);
int m = small.nextInt();
int n = large.nextInt();
int sums = 0 ;
int suml = 0;
int sum = 0;
for(int i = 0 ; i < m ; i ++){
sums += a[i];
System.out.print(a[i]+"*");
}
for(int i = 0 ; i < n ; i ++){
suml += a[i];
System.out.print(a[i]+" ");
}
sum = suml - sums;
System.out.println(sum);
}
}
加個變量控制一下就行了。
public class All {
public static void main(String[] args) {
int a[] = new int[200];
int index = 0;
// 將前200個數中的素數提取出來放入數組a中
for (int i = 1; i < 200; i++) {
boolean isPrime = true;
for (int k = 2; k < i; k++) {
if (i % k == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
a[index++] = i;
System.out.println(a[index-1]); // 打印確認
}
}
// 輸入兩個數 m,n 求第m個素數到底n個素數之間的素數和
Scanner small = new Scanner(System.in);
Scanner large = new Scanner(System.in);
int m = small.nextInt();
int n = large.nextInt();
int sums = 0;
int suml = 0;
int sum = 0;
for (int i = 0; i < m; i++) {
sums += a[i];
System.out.print(a[i] + "*");
}
for (int i = 0; i < n; i++) {
suml += a[i];
System.out.print(a[i] + " ");
}
sum = suml - sums;
System.out.println(sum);
}
}