Skip to code
Skip to analysis

This is a explanation of this problem from USACO's training website. I have converted it to markdown. Please do not just copy code; you will not learn anything; at least type it out and understand so you can do it yourself in the future!

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

CODE

Java


C++


Pascal



ANALYSIS

Russ Cox

We use a recursive search to build superprimes of length n from superprimes of length n-1 by adding a 1, 3, 7, or 9. (Numbers ending in any other digit are divisible by 2 or 5.) Since there are so few numbers being tested, a simple primality test suffices.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

FILE *fout;

int
isprime(int n)
{
	int i;

	if(n == 2)
		return 1;

	if(n%2 == 0)
		return 0;

	for(i=3; i*i <= n; i+=2)
		if(n%i == 0)
			return 0;

	return 1;
}

/* print all sprimes possible by adding ndigit digits to the number n */
void
sprime(int n, int ndigit)
{
	if(ndigit == 0) {
		fprintf(fout, "%d\n", n);
		return;
	}

	n *= 10;
	if(isprime(n+1))
		sprime(n+1, ndigit-1);
	if(isprime(n+3))
		sprime(n+3, ndigit-1);
	if(isprime(n+7))
		sprime(n+7, ndigit-1);
	if(isprime(n+9))
		sprime(n+9, ndigit-1);
}

void
main(void)
{
	int n;
	FILE *fin;

	fin = fopen("sprime.in", "r");
	assert(fin != NULL);
	fout = fopen("sprime.out", "w");
	assert(fout != NULL);

	fscanf(fin, "%d", &n);

	sprime(2, n-1);
	sprime(3, n-1);
	sprime(5, n-1);
	sprime(7, n-1);
	exit (0);
}

Back to top