Prime number list checker

1 Ansicht (letzte 30 Tage)
James Blackwell
James Blackwell am 18 Aug. 2016
Kommentiert: James Blackwell am 18 Aug. 2016
Ok so just for fun and practice I have been having a go at creating a prime number checker. I have been successful in making it work for a specific number. The code is here.
#To test if number is prime
prompt = input("number to test if prime: ");
n = prompt;
i = 2; #start of mod test
t = floor(sqrt(n));
counter = 0;
tic
for i = 2:t
if mod(n,i) == 0
disp('n is not prime')
break
else
counter = (counter + 1);
end
end
if counter == t-1
disp('n is prime')
end
toc
I then tried to make a program which would test a range of numbers. It's been successful for n=10, but when I go higher than that it doesn't seem to pick up the primes. I'm not sure where I'm going wrong.
#Want to test numbers 2:n if they're prime
prompt = input("max number to test: ");
n = prompt;
l = 2; #start of mod test
counter = 0;
tic
for i = 2:n #cycle to test 2 up to n
t = floor(sqrt(i)) #Only need to test up to root of number
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1 # if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
counter = 0;
end
end
toc
Any help in getting it to work for larger values would be greatly appreciated and also any ways to make the code more efficient. The top program can test 982451653 in 0.268 seconds on my laptop.

Akzeptierte Antwort

James Tursa
James Tursa am 18 Aug. 2016
Your code for resetting "counter" is inside an if-test. You need to move it so that it always executes. E.g.,
%#Want to test numbers 2:n if they're prime
prompt = input('max number to test: ');
n = prompt;
l = 2; %#start of mod test
counter = 0;
tic
for i = 2:n %#cycle to test 2 up to n
t = floor(sqrt(i)); %#Only need to test up to root of number
counter = 0; % <-- Moved from below
for l = 2:t
if mod(i,l) == 0
break
else
counter = (counter + 1);
end
end
if counter == t-1 %# if tested up to the root of the number, it must be prime
prime = sprintf('%d is prime', round(i));
disp(prime)
% counter = 0; % <-- Moved to up above
end
end
toc
  1 Kommentar
James Blackwell
James Blackwell am 18 Aug. 2016
Thank you so much James, It has been bugging me all day. Can't believe it was something so simple!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu MATLAB finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by