1.3.4 Prime Cryptarithm

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    * *
    -------
      * * *         <-- partial product 1
    * * *           <-- partial product 2
    -------
    * * * *

Digits can appear only in places marked by `*'. Of course, leading zeroes are not allowed.

Note that the 'partial products' are as taught in USA schools. The first partial product is the product of the final digit of the second number and the top number. The second partial product is the product of the first digit of the second number and the top number.

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: makeeca1
PROG: crypt1
LANG: PASCAL
}
program crypt1;
var ss:set of 0..9;
    n,i,b,c,d,e,ans,x,y:longint;
    a:array[1..10]of integer;
function ok(xx,yy:longint):boolean;
var i:longint;s:string;
begin
  str(xx,s);
  if length(s)<>yy then exit(false);
  for i:=1 to length(s)do
  if not(ord(s[i])-48 in ss) then exit(false);
  exit(true);
end;
begin
  assign(input,'crypt1.in');reset(input);
  assign(output,'crypt1.out');rewrite(output);
  readln(n);ss:=[];ans:=0;
  for i:=1 to n do begin read(a[i]); ss:=ss+[a[i]];end;
  for i:=1 to n do
    for b:=1 to n do
      for c:=1 to n do
        for d:=1 to n do
          for e:=1 to n do
          begin
            x:=a[i]*100+a[b]*10+a[c];
            y:=a[d]*10+a[e];
              if (ok(x*a[e],3))and(ok(x*a[d],3))and(ok(x*y,4))then inc(ans);
          end;
  writeln(ans);
  close(output);
end.

posted on 2012-10-03 14:52  makeecat  阅读(203)  评论(0编辑  收藏  举报