package main
import (
"fmt"
"math"
"net/http"
"strconv"
)
func isPrime(num int) bool {
if num <= 1 {
return false
}
if num <= 3 {
return true
}
if num%2 == 0 || num%3 == 0 {
return false
}
i := 5
for i*i <= num {
if num%i == 0 || num%(i+2) == 0 {
return false
}
i += 6
}
return true
}
func checkPrimeHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
numberStr := r.Form.Get("number")
number, err := strconv.Atoi(numberStr)
if err != nil {
http.Error(w, "Invalid input: "+err.Error(), http.StatusBadRequest)
return
}
isPrime := isPrime(number)
if isPrime {
fmt.Fprintf(w, "%d is a prime number.", number)
} else {
fmt.Fprintf(w, "%d is not a prime number.", number)
}
}
func main() {
http.HandleFunc("/check_prime", checkPrimeHandler)
fmt.Println("Server running on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
Explanation:
Function isPrime(n int) bool
:
- Parameters: Takes an integer
n
as input. - Returns: Returns
true
ifn
is a prime number, otherwisefalse
.
Steps to Determine Primality:
- Edge Cases:
- Numbers less than or equal to 1 are not prime (
false
). - Handle small primes (2 and 3) directly (
true
). - Even numbers and multiples of 3 (except 2 and 3) are not prime (
false
).
- Numbers less than or equal to 1 are not prime (
- Trial Division:
- Loop through potential divisors starting from 5 up to
sqrt(n)
, checking bothi
andi+2
. - Increment
i
by 6 in each iteration to skip even numbers (since even numbers were already checked).
- Loop through potential divisors starting from 5 up to
- Efficiency:
- This approach checks divisibility up to the square root of
n
, which reduces the number of iterations compared to checking all numbers up ton-1
.
- This approach checks divisibility up to the square root of
main
Function:
- Test Cases: Tests the
isPrime
function with a list of prime numbers and non-prime numbers. - Additional Test Cases: Includes edge cases and larger numbers to verify the correctness of the
isPrime
function.
Output:
The program will output whether each number in the test cases is prime or not.
How to Run:
To run the program, save it to a file (e.g., prime.go
) and execute:
go run prime.go
Summary:
This GoLang program efficiently determines whether a given number is prime using trial division up to the square root of the number, ensuring optimal performance for large inputs.
Truly quite a lot of very good advice!
casino en ligne
Really a lot of terrific advice!
meilleur casino en ligne
Factor nicely used!.
meilleur casino en ligne
You reported this perfectly.
casino en ligne fiable
Many thanks! Good information.
casino en ligne
You actually expressed it superbly.
casino en ligne
Valuable knowledge, Kudos!
casino en ligne francais
Wow lots of fantastic tips!
casino en ligne fiable
Nicely put. Many thanks.
casino en ligne fiable
Thanks a lot! I appreciate this.
casino en ligne