Skip to content

Instantly share code, notes, and snippets.

@HabaCo
Created June 10, 2014 13:02
Show Gist options
  • Save HabaCo/99abf49ba966d41d4f7f to your computer and use it in GitHub Desktop.
Save HabaCo/99abf49ba966d41d4f7f to your computer and use it in GitHub Desktop.
讀檔&找質數
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
// 找質數
public class Q940303 {
public static void main(String[] args) throws FileNotFoundException {
String fileName = "940303.SM";
File f = new File(fileName);
Scanner sc = new Scanner(f);
while (sc.hasNext()){
int n = sc.nextInt();
System.out.print(n + " ");
if (isPrime(n))
System.out.println("is a prime number.");
else
System.out.println("is not a prime number.");
}
sc.close();
}
public static boolean isPrime(int n){
for (int i=2; i<n; i++){
if (i*i>=n) break; // 若 i^2 > n 則停
if (n%i == 0) return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment