RFC

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

POJ3006

 1 import java.util.Scanner;
2 import java.util.StringTokenizer;
3
4 public class _3006 {
5
6 public static boolean isPrime(int n) {
7 if (n < 2)
8 return false;
9 for (int i = 2; i * i <= n; i++) {
10 if (i * (n / i) == n)
11 return false;
12 }
13 return true;
14 }
15
16 public static void main(String[] args) {
17 int a, d, n;
18 Scanner sc = new Scanner(System.in);
19 while (sc.hasNextLine()) {
20 StringTokenizer st = new StringTokenizer(sc.nextLine(), " ");
21 while (st.hasMoreTokens()) {
22 a = Integer.parseInt(st.nextToken());
23 d = Integer.parseInt(st.nextToken());
24 n = Integer.parseInt(st.nextToken());
25 if (a == 0 && d == 0 && n == 0) {
26 return;
27 }
28
29 int i = 0;
30 if(isPrime(a))i++;
31 for(;i<n;){
32 a+=d;
33 if(isPrime(a))i++;
34 }
35 System.out.println(a);
36
37 }
38 }
39 }
40 }



小结:

1.求解本题时看错了题目,以为

[;a+d,a+2d,\cdots , a+nd,\cdots ;]

这样的序列;结果对于a为素数的情况错误,反而以为是isPrime错误,太不应该了。

2.题目中要求a和d是互素的,可以在24和25行间加

assert(gcd(a,d)==1);

对应的代码

public static int gcd(int a, int b){
if(a<b)return gcd(b,a);
if(b==0)return a;
return gcd(b,a%b);
}

对于eclipse,需要在运行参数配置中在jvm参数中加-ea才有用。



posted on 2012-03-10 13:02  hongxuchen  阅读(166)  评论(0编辑  收藏  举报
无觅相关文章插件,快速提升流量