How to determine if a number is prime?
Show older comments
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 Comments
Rik
on 1 May 2019
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).
This particular question has been already asked numerous times in this forum. You can see some of the old posts:
The answers given in these posts will help you in making your program.
Accepted Answer
More Answers (1)
% 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);
disp(prime_indices)
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!