Go Program to Check Prime Number with Example
% operator; for example, func isPrime(n int) bool { if n <= 1 { return false } for i := 2; i*i <= n; i++ { if n % i == 0 { return false } } return true }.Examples
How to Think About It
Algorithm
Code
package main import ( "fmt" "math" ) func isPrime(n int) bool { if n <= 1 { return false } for i := 2; i*i <= n; i++ { if n%i == 0 { return false } } return true } func main() { n := 17 if isPrime(n) { fmt.Printf("%d is a prime number\n", n) } else { fmt.Printf("%d is not a prime number\n", n) } }
Dry Run
Let's trace the number 17 through the code to see how it checks for primality.
Check if number is <= 1
17 is greater than 1, so continue.
Calculate square root limit
Square root of 17 is approximately 4.12, so loop from 2 to 4.
Loop and check divisibility
Check 17 % 2, 17 % 3, 17 % 4; none are zero.
No divisors found
Return true, 17 is prime.
| i | n % i | Divides evenly? |
|---|---|---|
| 2 | 17 % 2 = 1 | No |
| 3 | 17 % 3 = 2 | No |
| 4 | 17 % 4 = 1 | No |
Why This Works
Step 1: Exclude numbers less than 2
Numbers less than or equal to 1 are not prime by definition, so we return false immediately.
Step 2: Check divisors up to square root
We only check divisors up to the square root because any factor larger than that would have a matching smaller factor already checked.
Step 3: Return result based on divisibility
If any divisor divides the number evenly, it is not prime; otherwise, it is prime.
Alternative Approaches
package main import "fmt" func isPrime(n int) bool { if n <= 1 { return false } for i := 2; i < n; i++ { if n%i == 0 { return false } } return true } func main() { fmt.Println(isPrime(17)) }
package main import "fmt" func sieve(n int) []bool { prime := make([]bool, n+1) for i := 2; i <= n; i++ { prime[i] = true } for p := 2; p*p <= n; p++ { if prime[p] { for i := p * p; i <= n; i += p { prime[i] = false } } } return prime } func main() { primes := sieve(20) for i := 2; i <= 20; i++ { if primes[i] { fmt.Printf("%d is prime\n", i) } } }
Complexity: O(√n) time, O(1) space
Time Complexity
The loop runs up to the square root of n, so the time complexity is O(√n). This is because any factor larger than the square root would have a corresponding smaller factor already checked.
Space Complexity
The program uses a fixed amount of extra space regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
Checking divisibility up to the square root is faster than checking up to n-1. The sieve method is faster for checking many numbers but uses more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Check up to √n | O(√n) | O(1) | Single number primality check |
| Check up to n-1 | O(n) | O(1) | Simple but slower primality check |
| Sieve of Eratosthenes | O(n log log n) | O(n) | Finding all primes up to n |