matlab 欧拉计划 32
程序员文章站
2022-03-31 20:49:06
...
problem 32
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.
思路
- 要求:1到9每个数字仅出现一次,且以乘积形式表现;
- 乘数,被乘数和积一共有九位,经排除筛选可得两种情况:1位×4位=4位;2位×3位=4位。由此确定两个循环;
- 判断1到9中每个数是否只出现了一次:可将三个数连接成字符串与‘123456789’相交比较,若相交后所得字符串长度为9,则为所求。
(方法比较笨,如果有好建议欢迎提出。)
代码
clc;clear all;
t=[];
for i=1:9
for j=1234:9876
y=i*j;
i1=num2str(i);j1=num2str(j);y1=num2str(y);m=[i1 j1 y1];
if y<1e4&&y>1e3
%%%判断重复
if length(intersect(m,'123456789'))==9
t=[t y];
end
end
end
end
for i=12:98
for j=123:987
y=i*j;
i1=num2str(i);j1=num2str(j);y1=num2str(y);m=[i1 j1 y1];
if y<1e4&&y>1e3
%%%判断重复
if length(intersect(m,'123456789'))==9
t=[t y];
end
end
end
end
sum(unique(t))
下一篇: MATLAB数据拟合