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
分析:按照给出的限制条件一一剪纸,循环所有的情况,符合题意count加一
代码如下:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
bool use[10];
bool check(int);
int main()
{
ifstream cin("crypt1.in");
ofstream cout("crypt1.out");
int n,i,k;
cin>>n;
memset(use,0,sizeof(use));
for(i=0;i<n;i++)
{
cin>>k;
use[k]=1;
}
int count=0,j;
for(i=100;i<=999;i++)
{
if(check(i))
{
for(j=10;j<=99;j++)
{
if(i*j>9999)
continue;
if(check(j))
{
int x,y;
x=j;
y=j/10;
if(x*i>999||y*i>999)
continue;
if(check(x*i)&&check(y*i))
{
if(check(i*j))
{
count++;
//printf("i=%d j=%d \n",i,j);
}
}
}
}
}
}
cout<<count<<endl;
return 0;
}
bool check(int a)
{
int x;
while(a!=0)
{
x=a % 10;
if(use[x]==0)
return 0;
a=a/10;
}
return 1;
}
本文介绍了一种解决特定类型的算术谜题——Cryptarithm的方法。通过编程方式寻找使用指定数字子集的所有可能解。文章包含了一个示例程序,演示了如何验证解的有效性并计算所有可能的解。
700

被折叠的 条评论
为什么被折叠?



