-2

我正在努力使我的程序正常工作。它适用于素数。

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

我相信这是正确的格式,(显然我可能错了,因为它不起作用),我一直试图修复它无济于事。任何帮助将不胜感激,并且解释我做错了什么(我很确定它与微妙的格式有关)也会很棒。

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
4

3 回答 3

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
于 2013-09-05T13:43:57.913 回答
1

Matlab 有一个factor函数可以执行您的代码尝试执行的操作

p = factor(10)

返回 2、5 和

p = factor(11)

返回 11。

你所要做的就是测试length

if length(p) == 1

用于true素数。

于 2013-09-05T13:41:44.830 回答
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 = [];
于 2013-09-05T13:50:39.700 回答