a121.
質數又來囉
| From: [118.160.26.194] |
發表日期
:
2012-12-16 07:53
import java.util.LinkedList;
import java.util.Scanner;
public class JAVA {
public static void main(String args[]) {
math ma = new math();
ma.math();
}
}
class math {
public void math() {
Scanner sc = new Scanner(System.in);
check c = new check();
c.AddPrime(2);
c.AddPrime(3);
int number_1 = 2;
int number_2 = 2;
int num = 0;
while (sc.hasNext()) {
number_1 = sc.nextInt();
number_2 = sc.nextInt();
if (number_1 == 2) {
if (number_2 == 3) {
num = 2;
} else if (number_2 == 2) {
num = 1;
}
} else if (number_1 % 2 == 0) {
number_1 = number_1 + 1;
} else {
}
for (int i = number_1; i <= number_2; i += 2) {
num = num + c.check(i);
}
if (number_2 != 1) {
System.out.println(num);
} else {
System.out.println("0");
}
num = 0;
}
}
}
class check {
LinkedList<Integer> prime = new LinkedList<Integer>();
public void AddPrime(int number) {
prime.add(number);
}
public int check(int number) {
int sq = (int) Math.sqrt(number);
int result = 0;
if (sq > prime.getLast()) {
for (int i = prime.getLast(); i <= sq; i += 2) {
check_sub2(i);
}
result = check_sub1(number);
} else {
result = check_sub2(number);
}
return result;
}
public int check_sub1(int number) {
int i = 0;
while (true) {
if (number % prime.get(i) == 0) {
// System.out.println(number + "is not prime");
number = 0;
break;
} else if (prime.get(i) == prime.getLast()) {
if (number > prime.getLast()) {
prime.add(number);
} else {
}
// System.out.println(number + "is prime");
number = 1;
break;
}
i++;
}
return number;
}
public int check_sub2(int number) {
int i = 0;
int sq = (int) Math.sqrt(number);
while (true) {
if (number % prime.get(i) == 0) {
// System.out.println(number + "is not prime");
number = 0;
break;
} else if (sq <= prime.get(i)) {
if (number > prime.getLast()) {
prime.add(number);
} else {
}
// System.out.println(number + "is prime");
number = 1;
break;
}
i++;
}
return number;
}
}
一樣WA,不過這次我沒把握到底是不是正確,原則上來說,我找不到哪邊錯,冏.