M-File
fprintf('\n\nn!\n')
for i=[1:length(timearray)]
fprintf('%s \t %d \n', stringarray{i},factorial(timearray(i)))
end
Output
n!
microsecond 1
minute Inf
hour Inf
day Inf
month Inf
year Inf
century Inf
I’m trying to calculate the number of steps an algorithm that runs at n! takes at the above intervals (assuming 1 step = 1 microsecond). However, I am unable to get fprintf to display meaningful results.
Switching to fprintf('%s \t %bu \n', stringarray{i},factorial(timearray(i))) gave me some numbers, but I suspect they are wrong.
%bu Output
n!
microsecond 04607182418800017408
minute 09218868437227405312
hour 09218868437227405312
day 09218868437227405312
month 09218868437227405312
year 09218868437227405312
century 09218868437227405312
Disclaimer: I wrote this program to solve a homework problem, however the homework never specified to write a program.
Thanks for any help!
Mike
The problem is likely not with printing per se, but that the factorial computation itself is overflowing. Try just evaluating the value instead of printing it in the loop; you’ll find that the factorial function overflows after 170!.
One simple way to circumvent this is by returning the log-factorial instead:
Then you can compare values on vastly different scales without worrying about overflow. Note: the above function is not vectorized so it will only work with a single value input; if you need to work with array values then there appear to be other solutions already available.