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 primeprompt = input("number to test if prime: ");n = prompt;i = 2; #start of mod testt = floor(sqrt(n));counter = 0;ticfor i = 2:t if mod(n,i) == 0 disp('n is not prime') break else counter = (counter + 1); endendif counter == t-1 disp('n is prime')endtoc
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 primeprompt = input("max number to test: ");n = prompt;l = 2; #start of mod testcounter = 0;ticfor 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; endendtoc
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.
Best Answer