Algorithm, Data structure/Solved Algorithmic Problem

USACO 1.5 - Superprime Rib

JaykayChoi 2016. 6. 28. 21:30

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



출처: http://train.usaco.org/


뒷 자리를 하나씩 제거해도 소수인 숫자를 Superprime 이라 한다. 자릿수가 정해질 경우 해당되는 모든 숫자를 출력하시오.


재귀함수를 통해 Superprime 을 만들어가는 방법으로 풀어봤습니다.



my solving

c++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
 
vector<int> ret;
 
bool isPrime(int number)
{
    if (number == 1)
        return false;
    if (number == 2)
        return true;
 
    if (number % == 0)
        return false;
 
    int sqrtn = int(sqrt(number));
 
    for (int div = 3; div <= sqrtn; div += 2)
        if (number % div == 0)
            return false;
    return true;
}
 
void makePrime(int remainingDegit, int number)
{
    if (remainingDegit == 0)
    {
        ret.push_back(number);
        return;
    }
 
    for (int i = number * 10 + 1; i <= number * 10 + 9; i++)
    {
        if (isPrime(i))
            makePrime(remainingDegit - 1, i);
    }
}
 
int main()
{
    ifstream fin("sprime.in");
    ofstream fout("sprime.out");
 
    int length;
    fin >> length;
 
 
    makePrime(length, 0);
 
    sort(ret.begin(), ret.end());
 
    for (vector<int>::iterator it = ret.begin(); it != ret.end(); it++)
        fout << *it << endl;
 
    fin.close();
    fout.close();
    return 0;
}
cs