欧拉计划(Project Euler)第二十一题 matlab 21
程序员文章站
2022-03-31 20:46:52
...
原题目:
Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
分析:
定义比较绕 ,但其实就是数甲的所有除了本身的因数的和等于数乙,同时数乙所有除了本身的因数的和等于数甲,则二者就是Amicable numbers,即亲和数。通过先求出一个数的所有除了本身的因数的和,并在对和求所有除了本身的因数的和,相加即可。
额外需要注意的是,每对亲和数都被加了两遍,故结果需除以2.
此外,亲和数是不包括完全数(它所有的真因子的和恰好等于它本身)的,故需注意加上数甲不等于数乙的要求。
a=[];
b=0;
c=0;
d=0;
for i=1:1:10000
for j=1:i/2
if mod(i,j)==0
a=[a,j];
end
end
b=sum(a);
a=[];
for k=1:b/2
if mod(b,k)==0
a=[a,k];
end
end
c=sum(a);
a=[];
if i==c&&b~=c
d=d+i+b;
end
end
d=d/2
最后输出结果是31626
上一篇: Matlab中的元胞数组