此代码使用matlab编程
Problem20所用时间为0.95332秒
Problem20的答案为648%题目20:算出100!的各位之和
function Output=Problem20(Input)
tic
if nargin==0
Input=100;
end
Factorial=1;%阶乘数
for ii=2:Input
Temp=Mul(Factorial,ii);
Factorial=Temp;
end
toc
Output=sum(Factorial);
disp('此代码使用matlab编程')
disp(['Problem20所用时间为',num2str(toc),'秒'])
disp(['Problem20的答案为',num2str(Output)])
end
%% 子函数
%此函数定义矩阵与数的乘法
function Output=Mul(Input,factor)
if nargin==0
Input=[1 2];%大数矩阵
factor=88;%数
end
L=length(Input);
Input=Input*factor;
for ii=L:-1:2
if Input(ii)>=10
Str=num2str(Input(ii));
Input(ii-1)=Input(ii-1)+(Input(ii)-str2double(Str(end)))/10;
Input(ii)=str2double(Str(end));
end
end
if Input(1)>=10
Front=str2num(num2str(Input(1))')';%对第一位进行处理
Output=[Front,Input(2:end)];
else
Output=Input;
end
end
|