Loops and conditions together can test a property of a number.
What to build
A program that tests numbers for primality.
Requirements
- Read q, then q numbers.
- For each number n print
n is primeorn is not prime.
Input
Line 1: q. Then q whole numbers.
Output
q lines.
Constraints
1 ≤ q ≤ 30; 1 ≤ n ≤ 100000.
Example
Input:
4
1 2 15 17
Output:
1 is not prime
2 is prime
15 is not prime
17 is prime
Why it works
If n has a divisor, it has one that is at most the square root of n, so the loop can stop when d * d > n. This is much faster than trying every number below n.
Examples
Example 1 · Input
4 1 2 15 17
Expected output
1 is not prime 2 is prime 15 is not prime 17 is prime
Example 2 · Input
2 97 100
Expected output
97 is prime 100 is not prime
Hints
Hint 1
A number below 2 is not prime.
Hint 2
Try divisors d from 2 while d * d <= n; if n % d == 0 it is not prime.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
func main() {
var q int
fmt.Scan(&q)
for i := 0; i < q; i++ {
var n int
fmt.Scan(&n)
prime := n >= 2
for d := 2; d*d <= n; d++ {
if n%d == 0 {
prime = false
break
}
}
if prime {
fmt.Printf("%d is prime\n", n)
} else {
fmt.Printf("%d is not prime\n", n)
}
}
}