Pandigital products
We shall say that an n-digit number is pandigital if it makes use of all the digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through 5 pandigital.
The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing multiplicand, multiplier, and product is 1 through 9 pandigital.
Find the sum of all products whose multiplicand/multiplier/product identity can be written as a 1 through 9 pandigital.
HINT: Some products can be obtained in more than one way so be sure to only include it once in your sum.
题目:
如果一个 n 位数使用了 1 到 n 中每个数字且只使用了一次,我们称其为 pandigital。例如,15234 这个五位数,是 1 到 5 pandigital 的。
7254 是一个不寻常的数,因为:39 × 186 = 7254 这个算式的乘数,被乘数和乘积组成了一个1到 9 的 pandigital 组合。
找出所有能够组合成 1 到 9 pandigital 的乘法算式中乘积的和。
提示: 有的乘积数字能够被多个乘法算式得到,所以在计算时要记得只计算它们一次。
这个题目要求的是通过两个数的成绩得到一个数,然后这三个数的每一位可以凑成1-9的数字,这就是题目要求的数,然后求的他们的和;
现在知道的求的3个数的位数一共有9位,那么现在就去判断开始和上届;
1位数去乘以4位数可以得到4位数,
2位数去乘以3位数可以得到4位数
3位数去乘以2位数可以得到4位数
4位数去乘以1位数可以得到4位数
好的可以发现,1位数乘以4位数,2位数乘以3位数,才可以有机会找到满足题目的数字,那么就相当于,外层循环1-99,里层循环100-9999;
然后去判断3个数是否满足题目条件,还有乘积是否重复;
#include <stdio.h> #include <math.h> int find_repeat(int a, int *num) {//判断位置是否有重复 while (a) { if (num[a % 10]) return 0; num[a % 10] = 1; a /= 10; } return 1; } int get_len(int a) {//判断数字位数 return log10(a) + 1; } int is_pandigital_num(int a, int b, int c) {//判断位置是否重复 int num[10] = {0}; num[0] = 1; if (!find_repeat(a, num)) return 0; if (!find_repeat(b, num)) return 0; if (!find_repeat(c, num)) return 0; return 1; } int main() { int fact[10000] = {0};//记录乘积,如果重复就不加上了 int ans = 0; for (int i = 1; i < 100; i++) { for (int j = i < 10 ? 1000 : 100; j < 10000; j++) { if(get_len(i) + get_len(j) + get_len(i * j) != 9) continue;//不等于9位就不进行下面的判断了 if (!is_pandigital_num(i, j, i * j) || fact[i * j]) continue;//如果发现重复,或者乘积重复就不进行下面的加和了 ans += i * j; fact[i * j] = 1; } } printf("%d\n", ans); return 0; }
最终答案:45228