我的功能代码有什么问题(MATLAB / OCTAVE)

时间:2013-09-05 13:22:16

标签: matlab function octave

我正在尝试让我的程序正常运行。这是素数。

下面是我的功能,然后是我的主程序

我相信这是正确的格式化(显然我可能错了因为它不起作用)而且我一直试图修复它无济于事。任何帮助都将非常受欢迎,我对错误的解释(我很确定它与微妙的格式有关)也很好。

function [answer,primefactors ] = primey1 (N)
for i=2:(N-1)
    A(i-1)=rem(N,i);
end
A;
if(all(A)==1)
    answer=['Yes']
    primefactors=[1,N]
elseif(all(A)==0)
    answer=['No']
    fac=[]
    for i=2:N
        q=0;
        while N/i==floor(N/i)
            N=N/i;
            q=q+1;
        end
        if q>0
            fac=[fac,i]
            if N==1
                break
                primefactors=[fac]
            end
        end
    end
end

endfunction

3 个答案:

答案 0 :(得分:4)

正如Magla所说,MATLAB附带了primesfactor函数,您至少可以使用这些函数来比较您的实现和/或检查您的结果。

无论如何,至于你的代码,试试这个:

function [answer, primefactors] = primey1(N)

    % Use vectorization for simple cases such as these: 
    A = rem(N,2:N-1);

    if all(A)
        answer = 'Yes';
        primefactors = [1,N];

    % Re-wrote this entire section. There were a bunch of things wrong with it: 
    % the order of commands was wrong, variables were not assigned for some N, 
    % etc. Just compare the two implementations
    else
        answer = 'No';        
        primefactors = [];

        for ii = 2:N

            q = 0;            
            while N/ii == floor(N/ii)
                N = N/ii;
                q = q+1;
            end

            if q > 0
                primefactors = [primefactors,ii]; %#ok<AGROW>
                if N==1                   
                    break;
                end
            end

        end

    end

end

答案 1 :(得分:1)

Matlab有一个factor函数可以完成代码尝试的操作

p = factor(10)

返回2,5 和

p = factor(11)

返回11。

您只需要测试length

if length(p) == 1

是素数的true

答案 2 :(得分:1)

@Rody提供的解决方案应该完成这项工作,理论上甚至比这更有效,但为了说明初始化的概念,我建议你在函数启动后立即初始化函数的输出变量。在你的情况下,这意味着我建议启动这样的代码:

function [answer, primefactors] = primey1(N)
% Function to determine whether a number is prime and which prime factors it has

% Assign default values
answer = 'No';
primefactors = [];