patternMinor
"Is a number prime?"
Viewed 0 times
primenumberstackoverflow
Problem
I've come up with a very efficient way of finding if a number is prime, using TI-BASIC for use with TI-83/84/+/SE calculators. I am trying to optimize it however possible.
A few notes:
:Input "NUMBER: ",A
:If A<2 or fPart(A
:Then
:Disp "INVALID INPUT"
:Stop
:End
:0→B
:2→I
:While I<A and not(B
:If 0=fPart(A/I
:1→B
:I+2→I
:If I=4
:3→I
:End
:If B
:Disp "NOT"
:Disp "PRIME"A few notes:
- Lines 2-6 are for validating input, and don't affect the effectiveness of the program.
- The closing
"s on line 4 and the last two lines are not necessary, but I added them so the syntax would highlight nicely here.
- Lines 12-14 are for speeding up the loop doubly; instead of incrementing by
1each time, it is by2, with theIfto offset the4to3on the first run.
- The
not(Bwas very efficient, to end the loop whenever a match to identify the number as a composite number is found.
Solution
I do not speak TI-BASIC, so I cannot review the style, coding conventions etc. But there are two possible optimizations:
-
If a number
equal to
with:
This reduces the number of trial divisions substantially if the input is a prime number.
-
Check the divisibility by
in each loop iteration.
-
If a number
A is composite then it must have a factor that is less than orequal to
√(A). So you can replace:While I<A and not(Bwith:
:√(A)→S
:While I≤S and not(BThis reduces the number of trial divisions substantially if the input is a prime number.
-
Check the divisibility by
2 first, and then loop just over the odd numbersI = 3, 5, 7, .... This saves you from checking:If I=4
:3→Iin each loop iteration.
Code Snippets
:While I<A and not(B:√(A)→S
:While I≤S and not(B:If I=4
:3→IContext
StackExchange Code Review Q#67607, answer score: 6
Revisions (0)
No revisions yet.