Создайте список простых чисел из диапазона ввода пользователем в Matlab. Условие игнорировать отрицательные числа, 0 и 1, если в списке - PullRequest
0 голосов
/ 11 января 2020

Я могу извлечь список простых чисел, но когда список имеет отрицательные числа, или 0 или 1, условие не работает. Пожалуйста, помогите мне исправить ошибку в этом коде. Подробное пошаговое объяснение для постановки условия приветствуется. Спасибо

clear 
clc
%Matlab program to give prime numbers in a given interval Ignoring 0, 1  and negative numbers if in the input range
start = input('Enter a starting number range:');
end_point = input('enter an ending number:');

list = start:end_point;  % Create a list having the range

prime = []; % initiate empty prime vector, prime numbers will be added to this list
for i = (1:length(list))
    fac = 0; % calculates the number of factors
    if list(i) <= 1 %Checks whether the number is less than or equal to 1
            fac = fac+1 % Assigns factor 1 and hence the algorithm ignores them from prime list 
            break
    for j = 2:list(i)/2
            if list(i) <= 1 %Checks whether the number is less than or equal to 1
                fac = fac+1 % Assigns factor 1 and hence the algorithm ignores them from prime list 
                break

%         if j == [] 
%             fac = fac + 1
%             break
        elseif mod(list(i),j) == 0 % checks whether a number is prime or not from the list
            fac = fac+1;
        else 
            fac = fac+0;
        end
    end
    if fac <1  % No factors between 2 and number\_checked/2 hence puts it in prime list 
        prime = [prime,list(i)];
    else 
        continue
    end

    end

1 Ответ

3 голосов
/ 11 января 2020

Вот пересмотренный код, основанный на вашем. У вас есть проблемы с использованием ошибок break и logi c при проверке простых чисел.

Я прокомментировал свой код, так что вы можете прочитать его для лучшего понимания. Надеюсь, что это поможет вам!

clear 
clc
%Matlab program to give prime numbers in a given interval Ignoring 0, 1  and negative numbers if in the input range
start = input('Enter a starting number range:');
end_point = input('enter an ending number:');

list = start:end_point;  % Create a list having the range

prime = []; % initiate empty prime vector, prime numbers will be added to this list
for i = 1:length(list)
    if list(i) <= 1 %Checks whether the number is less than or equal to 1 
      break
    elseif ismember(list(i),[2,3]) % check if it is 2 or 3. If yes, then added to prime
      prime = [prime, list(i)];
    else
      for fac = 2:list(i)/2 % fac is possible from 2 to list(i)/2 
        if mod(list(i),fac) == 0 % if fac is a fact of list(i), then it is not a prime, thus break the loop
            break
        else % otherwise, check if the next integer would be the factor
            fac = fac +1;
        end
      end
      if fac > list(i)/2  % No factors between 2 and number\_checked/2 hence puts it in prime list 
        prime = [prime,list(i)];
      end
  end
end

Дополнительно :

Если вы хотите использовать встроенную функцию MATLAB для простых чисел, isprime() может быть тебе нравится. В этом случае ваш код может быть упрощен, как показано ниже

clear 
clc
%Matlab program to give prime numbers in a given interval Ignoring 0, 1  and negative numbers if in the input range
start = input('Enter a starting number range:');
end_point = input('enter an ending number:');

list = start:end_point;  % Create a list having the range
prime = list(isprime(list));
...