CSC263 Computer Organization & Architecture I
Lab 3
Write a program that reads in numbers and prints a message telling
whether or not each number is prime. Recall that a prime number is
divisible only by itself and 1.
An easy (but not efficient!) method to determine whether a number N is
prime is to check whether any number smaller than N (other than 1) divides
N evenly. For example, if N is 20, you need to check whether 2, 3, ..., 19
divide 20 evenly. Actually, you only need to check those numbers less than
sqrt(n) (think about why this is true). If one of these numbers does divide n
evenly, then N is not prime.
It can be shown that all primes, other than 2 and 3, are of the form 6k - 1
or 6k + 1 for some k. (We will not prove this here.) This means that we can
use the following algorithm, which is a little more efficient than the brute
force method described above:
isPrime(n) {
if n == 1
return false
else if n == 2 or n == 3
return true
else if n mod 2 == 0 or n mod 3 == 0
return false
let i = 5
while i * i <= n {
if n mod i == 0 or n mod (i + 2) == 0
return false
i = i + 6
}
return true
}
Your program should prompt for numbers and use this algorithm to test
whether each number is prime. Stop the program when the user enters 0.