USACO1.5.3--Superprime Rib

Superprime Rib

Butchering Farmer John's cows always yields the best prime rib. You can tell prime ribs by looking at the digits lovingly stamped across them, one by one, by FJ and the USDA. Farmer John ensures that a purchaser of his prime ribs gets really prime ribs because when sliced from the right, the numbers on the ribs continue to stay prime right down to the last rib, e.g.:

     7  3  3  1

The set of ribs denoted by 7331 is prime; the three ribs 733 are prime; the two ribs 73 are prime, and, of course, the last rib, 7, is prime. The number 7331 is called a superprime of length 4.

Write a program that accepts a number N 1 <=N<=8 of ribs and prints all the superprimes of that length.

The number 1 (by itself) is not a prime number.

PROGRAM NAME: sprime

INPUT FORMAT

A single line with the number N.

SAMPLE INPUT (file sprime.in)

4

OUTPUT FORMAT

The superprime ribs of length N, printed in ascending order one per line.

SAMPLE OUTPUT (file sprime.out)

2333
2339
2393
2399
2939
3119
3137
3733
3739
3793
3797
5939
7193
7331
7333
7393
题解:赤果果的DFS啊。首位只可能是2,3,5,7,其余位只可能是1,3,5,7,9,偶数显然不是质数。每次把数加入当前数的末尾都判断一下是否是质数。
View Code
 1 /*
 2 ID:spcjv51
 3 PROG:sprime
 4 LANG:C
 5 */
 6 #include<stdio.h>
 7 int len;
 8 int is_prime(long n)
 9 {
10     long i;
11     if(n<2) return 0;
12     for(i=2; i*i<=n; i++)
13         if(n%i==0) return 0;
14     return 1;
15 }
16 void DFS(long sum,int step)
17 {
18     int i;
19     if(step>len) return;
20     if(step==len&&is_prime(sum))
21         printf("%ld\n",sum);
22     for(i=1; i<=9; i+=2)
23         if(is_prime(sum*10+i))
24             DFS(sum*10+i,step+1);
25 }
26 int main(void)
27 {
28     freopen("sprime.in","r",stdin);
29     freopen("sprime.out","w",stdout);
30     long i;
31     scanf("%d",&len);
32     for(i=2; i<=9; i++)
33     {
34         if(is_prime(i))
35             DFS(i,1);
36     }
37     return 0;
38 }

 

posted on 2013-01-31 11:02  仗剑奔走天涯  阅读(253)  评论(0编辑  收藏  举报

导航