Prime Cryptarithm
The following cryptarithm is a multiplication problem that can be solved by substituting digits from a specified set of N digits into the positions marked with *. If the set of prime digits {2,3,5,7} is selected, the cryptarithm is called a PRIME CRYPTARITHM.
* * *
x * *
-------
* * *
* * *
-------
* * * *
Digits can appear only in places marked by `*'. Of course, leading zeroes are not allowed.
Write a program that will find all solutions to the cryptarithm above for any subset of digits from the set {1,2,3,4,5,6,7,8,9}.
PROGRAM NAME: crypt1
INPUT FORMAT
| Line 1: |
N, the number of digits that will be used |
| Line 2: |
N space separated digits with which to solve the cryptarithm |
SAMPLE INPUT (file crypt1.in)
5
2 3 4 6 8
OUTPUT FORMAT
A single line with the total number of unique solutions. Here is the single solution for the sample input:
2 2 2
x 2 2
------
4 4 4
4 4 4
---------
4 8 8 4
SAMPLE OUTPUT (file crypt1.out)
1
{
ID:style71
PROG:crypt1
LANG:PASCAL
}
program crypt1;
var p1,p2,p3,p4,p5,n,i:integer;
sum:longint;
f1,f2:text;
num:array [1..9] of integer;
function ifin(k:integer):boolean;
var j:integer;
begin
for j:=1 to n do
if num[j]=k
then
begin
ifin:=true;
exit;
end;
ifin:=false;
end;
function pan(x:integer):boolean;
var l:integer;
begin
repeat
begin
l:=x mod 10;
if not(ifin(l))
then
begin
pan:=false;
exit;
end;
x:=x div 10;
end;
until x<1;
pan:=true;
end;
function try:boolean;
var a,b,s1,s2,s:integer;
begin
a:=num[p1]*100+num[p2]*10+num[p3];
b:=num[p4]*10+num[p5];
s1:=a*num[p4];
s2:=a*num[p5];
if (s1>=1000) or (s2>=1000)
then
begin
try:=false;
exit;
end;
if (not(pan(s1)))
then
begin
try:=false;
exit;
end;
if (not(pan(s2)))
then
begin
try:=false;
exit;
end;
s:=s1*10+s2;
if (s>=10000) or (not(pan(s)))
then
begin
try:=false;
exit;
end;
try:=true;
end;
begin
assign(f1,'crypt1.in');
assign(f2,'crypt1.out');
reset(f1);
rewrite(f2);
readln(f1,n);
sum:=0;
for i:=1 to n do
read(f1,num[i]);
for p1:=1 to n do
for p4:=1 to n do
if (num[p1]*num[p4]<10)
then
for p5:=1 to n do
if (num[p1]*num[p5]<10)
then
for p2:=1 to n do
for p3:=1 to n do
if try
then
inc(sum);
writeln(f2,sum);
close(f1);
close(f2);
end.