Hard Algorithms

Is it prime?

Read a whole number n of 1 or more. DISPLAY true if n is prime (it has exactly two divisors, 1 and itself) and false otherwise. Remember that 1 is not prime.

Input (one value per INPUT ())Expected output
7true
1false

Check runs all 4 tests. Press Run to try the program yourself: a box asks for each INPUT ().

Output


        
        
      

Variables

Show a solution
n ← INPUT ()
prime ← n > 1
d ← 2
REPEAT UNTIL (d * d > n OR NOT prime)
{
   IF (n MOD d = 0)
   {
      prime ← false
   }
   d ← d + 1
}
DISPLAY (prime)

Teachers: sign in as a teacher to add this exercise to a class, graded automatically.

Frequently asked questions

How do I solve this exercise?

Complete the starter code in the editor, press Run to try it (type values when INPUT () asks), then press Check to run every test. Step shows the program line by line with its variables.

Where is the solution?

Under the editor, in Show a solution. Try the exercise first: comparing your code with the solution afterwards is a good way to learn another approach.

AP is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site.