問題
Java實作
public static void test01(){
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int size = 0;
for (int i = a+1; i < b; i++) {
boolean flag = true;
if (i == 2){
System.out.print("2"+" ");
size++;
continue;
}
//優化
if (i % 2 == 0){
continue;
}
for (int j = 2; j < i; j++) {
if (i % j == 0) {
flag = false;
}
}
if (flag) {
System.out.print(i+" ");
size++;
}
if (size == 5) {
System.out.println();
size = 0;
}
}
}
- 時間複雜度:O(n^2)
- 空間複雜度:O(1)