C/C++練習7---求某個範圍內的所有素數
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
求小於n的所有素數,按照每行10個顯示出來。
Input
輸入整數n(n<10000)。
Output
每行10個依次輸出n以內(不包括n)的所有素數。如果一行有10個素數,每個素數後面都有一個空格,包括每行最後一個素數。
Sample Input
100
Sample Output
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Hint
請注意題目中求的是小於n的所有素數。
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int n, i, j, count;
n = reader.nextInt();
count = 0;
//1不是素數,查找素數從2開始
for(i = 2; i < n; i++)
{
if(isPrime(i))
{//若元素i爲素數,則輸出該數
if(count!= 0 && count%10 == 0)//此處加條件防止count=0時也會換行
{//每輸出10個數則換行
System.out.println();
}
System.out.print(i+" ");
count++;
}
}
reader.close();
}
private static boolean isPrime(int n)
{//判斷元素n是否爲素數的函數
boolean flag = true;
for(int i = 2; i <= Math.sqrt(n); i++)
{
if(n % i == 0)
{
flag = false;
break;
}
}
return flag;
}
}