How to determine if a number is prime?

조회 수: 19 (최근 30일)
Juan Zegarra
Juan Zegarra 2019년 5월 1일
답변: Ozkan 2023년 5월 8일
Hello, I was wondering if you can help how to determine if numbers from 0 to 100 are prime. Should I use loops? Please I am really confused with this homework.
  댓글 수: 2
Rik
Rik 2019년 5월 1일
There are many ways you could solve this. What was the exact assignment? I suspect you're not allowed to use the isprime function.
How would you solve this on paper? That's usually a good start for how to solve it in any programming language.
You can find guidelines for posting homework on this forum here (and there is also a lot of helpful advice on that page).
Raj
Raj 2019년 5월 2일
편집: Raj 2019년 5월 2일

댓글을 달려면 로그인하십시오.

채택된 답변

jahanzaib ahmad
jahanzaib ahmad 2019년 5월 2일
편집: jahanzaib ahmad 2019년 5월 2일
thats not difficult .try to solve it on paper first .for example u have a number 100 . how will u check that its prime or not ?
divide it with all numbers from 1 to 99 .. and if any time the remainder is zero its not a prime number
to divide 100 from 1 to 100 u can use for loop .
  댓글 수: 1
Rik
Rik 2019년 5월 2일
As is probably mentioned in the links posted above, you don't need to check up to 99, checking up to the square root of your number (and exiting the loop when you found a factor) will get you a big jump in performance.
An even better method would be to write a prime number sieve (use ismember to find the multiples).

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Ozkan
Ozkan 2023년 5월 8일
% First n terms of Fibonacci series
n = 55;
% Starting with the first two terms are 1 and 1
fibo = [1, 1];
% Calculate the remaining terms and add them into the serie
for i = 3:n
fibo(i) = fibo(i-1) + fibo(i-2);
end
% Create a pointer vector to point the prime numbers
prime_flags = false(size(fibo));
% Check if the term in the serie is a prime number
for i = 1:n
% Prime numbers start from 2, thus no need to check the first two terms
if i > 2
% Check each number
for j = 2:sqrt(fibo(i))
% If division has no remainder, it is not a prime number
if rem(fibo(i), j) == 0
break;
end
end
% If there is no integer divider then it is a prime number
if rem(fibo(i), j) ~= 0
prime_flags(i) = true;
end
end
end
% find the indices of prime flags
prime_indices = find(prime_flags);
disp(fibo);
1.0e+11 * Columns 1 through 19 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 Columns 20 through 38 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0001 0.0001 0.0001 0.0002 0.0004 Columns 39 through 55 0.0006 0.0010 0.0017 0.0027 0.0043 0.0070 0.0113 0.0184 0.0297 0.0481 0.0778 0.1259 0.2037 0.3295 0.5332 0.8627 1.3958
disp(prime_indices)
5 7 11 13 17 23 29 43 47

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by