找到n最大的自然数n!是精确计算的

时间:2017-08-04 03:47:50

标签: matlab

我开始使用matlab,我正在尝试学习语言是如何运作的。

我正在尝试找出如何找到n的最大自然数n!是精确计算的。我被允许使用Matlab函数factorial和intmax。

我正在使用Matlab版本2017a。

非常感谢

2 个答案:

答案 0 :(得分:4)

从技术上讲,您甚至不需要使用factorialintmax函数来解决此问题。以下是unsigned 64-bit integer type的示例:

total = uint64(1);  % Set the data type you want here
N = 1;
while (total == (total*(N+1))/(N+1))
  N = N+1;
  total = total*N;
end
disp(N)

输出:

 20    % Largest N for uint64 types that gives correct factorial(N)

这是有效的,因为数据类型对它们可以表示的数字的大小有一个上限。如果你使数字太大,它将在integer types的最大值处饱和,或者在floating-point types时失去精确度(关于精度here的一些有趣的相关信息)。上面的循环保持一个运行total,将阶乘存储到N并检查是否乘以然后将除以N+1给出相同的结果,如果初始乘法导致溢出/精度损失,则不会。

答案 1 :(得分:1)

可能的解决方案:

n=1;
Vec=[1];
IsAccurate=true;

while IsAccurate
    n=n+1;
    Vec(end+1)=n; %#ok<SAGROW>
    Factorial=prod(Vec); %multiply all vector elements
    IsAccurate=true;
    for i=1:n %test if division of factorial by number give correct result
        Number1=Factorial/Vec(i);
        Number2=prod(Vec([1:i-1,i+1:n]));
        Diff=Number1-Number2;
        IsAccurate=IsAccurate & Diff==0;
    end
end
disp(n)
相关问题