- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang program to find prime numbers in a given range
Examples
- Input num1=3 and num2=8 => Prime numbers are: 3, 5, 7
- Input num1=8 and num2=23 => Prime numbers are: 11, 13, 17, 19, 23
Approach to solve this problem
- Step 1: Define a function that accepts two numbers, num1 and num2, type is int.
- Step 2: Iterate between num1 and num2.
- Step 3: If the number is prime, then print that number, else break.
Program
package main import ( "fmt" "math" ) func printPrimeNumbers(num1, num2 int){ if num1<2 || num2<2{ fmt.Println("Numbers must be greater than 2.") return } for num1 <= num2 { isPrime := true for i:=2; i<=int(math.Sqrt(float64(num1))); i++{ if num1 % i == 0{ isPrime = false break } } if isPrime { fmt.Printf("%d ", num1) } num1++ } fmt.Println() } func main(){ printPrimeNumbers(5, 19) printPrimeNumbers(0, 2) printPrimeNumbers(13, 100) }
Output
5 7 11 13 17 19 Numbers must be greater than 2. 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
Advertisements