Problem 20 : Factorial digit sum

n! means n × (n − 1) × ... × 3 × 2 × 1

For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.

Find the sum of the digits in the number 100!

思路 :

看到题目便想到了使用matlab自带的factorial函数(阶乘函数),调用方式非常简单,比如说:

>>factorial(10)         ------这是输入

>>3628800                   ------输出结果

简直就是太强大了,那100的阶乘也是这种方法喽!其中有一步数据的处理就是把数字转换成字符串放入数组中,计算完成后再把字符串转换成数字就行了,第一步就是用num2str函数把数字转换成字符串,最后再用str2num或者str2double转换回来!

代码 : 

clear,clc;
tic
i = 1;
sum = 0;
a = factorial(100);
A = num2str(a,'%.0f')
for i = 1:length(A)
    sum = sum + str2num(A(i));
end
sum
toc

结果 :683(错误的示范),于是我用python写了一个代码,得到了正确的结果!

         648(正确的结果)

欧拉计划问题二十的matlab实现

为什么是这样的呢?大家帮忙看看,有什么地方不妥,导致结果错误!失之毫厘,谬以三十五(683-648=35)。希望大家帮忙看看,发表出自己的看法与建议,好让正确的结果浮出水面! 

相关文章: