Prime number list checker

1 次查看(过去 30 天)
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.

采纳的回答

James Tursa
James Tursa 2016-8-18
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 个评论
James Blackwell
James Blackwell 2016-8-18
Thank you so much James, It has been bugging me all day. Can't believe it was something so simple!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by