Algorithm for extracting prime numbers from within a range

4 views (last 30 days)
Attempting to code my shallow understanding on MATLAB, a prime number(P) should have remainders when divided by all numbers from 1 to P, with the exception of only 1 and P itself.
Hence the reasoning for the following algorithm I am trying to write in MATLAB script:
clc
num1 = input ('Key in start value: ')
num2 = input {'Key in end value: ')
for x = num1:num2;
if mod(x/(2:x-1) ~= >0;
x = primenum
end
fprintf ('%d\n', primenum)
end
The error encountered is (clearly the code is very badly written but I dont even know where the error is from the error encountered)
Error using mod
Not enough input arguments.
Error in Q2 (line 6)
if mod(x/(2:x-1) ~= 0;
There are many examples about testing prime numbers but I lack the intelligence to logically understand any of them and do not want to copy paste them blindly. It would be a great help to know if my approach can work.

Accepted Answer

Walter Roberson
Walter Roberson on 24 Jan 2016
mod(x/(2:x-1) ~= 0
is missing a ')'
mod() requires two arguments, the first the value to be tested, and the second the base to test against. For example,
mod(1234, 7)
It is legal to use a vector of values, such as
mod(1234, 1:1233)
The result of that would be a vector of results.
You can test a vector of values (such as the result of mod()) against a value such as 0,
mod(1234, 1:1233) ~= 0
and the result of that test will be a vector of logical results. When an "if" is asked to evaluate a vector of logical results, it considers the condition to be true if all of the values in the vector are true. This is often not what is desired, and even when it is desired it is usually confusing for the reader. You should read the documentation about all() and about any()
  1 Comment
Neonfox
Neonfox on 24 Jan 2016
You helped make my code work. I had been working on this for a few days because I wanted to solve it with my own little solution. Thank you very much. Seriously, thank you.

Sign in to comment.

More Answers (0)

Categories

Find more on Discrete Math in Help Center and File Exchange

Products

Community Treasure Hunt

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

Start Hunting!