- The Dev Loop
- Posts
- Go: Prime Number #1
Go: Prime Number #1
Go program that takes a number n as input and prints all the prime numbers from 1 to n
Problem: Write a Go program that takes a number n as input and prints all prime numbers from 1 to n. Prime Number: A prime number is a number greater than 1 that only has two divisors: 1 and itself. Example: Input: n = 30 Output: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 Hint: Use a basic for loop to iterate through numbers, and check if each number is divisible by any number other than 1 and itself.
Here's a Go program that takes a number n
as input and prints all the prime numbers from 1 to n
:
package main
import (
"fmt"
)
// Function to check if a number is prime
func isPrime(num int) bool {
if num <= 1 {
return false
}
// Check divisibility from 2 to the square root of num
for i := 2; i*i <= num; i++ {
if num%i == 0 {
return false
}
}
return true
}
func main() {
// Take input from the user
var n int
fmt.Print("Enter a number: ")
fmt.Scan(&n)
// Print prime numbers from 1 to n
fmt.Printf("Prime numbers between 1 and %d are:\n", n)
for i := 2; i <= n; i++ {
if isPrime(i) {
fmt.Print(i, " ")
}
}
fmt.Println() // To print a new line after the list of primes
}
Explanation:
isPrime function: This function checks if a given number is prime. It checks divisibility starting from 2 up to the square root of the number (
i*i <= num
). If any number between 2 and the square root dividesnum
evenly, the number is not prime.Main function:
The program takes an integer input
n
from the user.It then loops through all numbers from 2 to
n
and uses theisPrime
function to check if the current number is prime.If the number is prime, it is printed.
Example Output:
Enter a number: 30
Prime numbers between 1 and 30 are:
2 3 5 7 11 13 17 19 23 29
Let me know if you need further explanation or modifications!