mirror of https://github.com/knative/docs.git
93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
/*
|
|
Copyright 2017 The Knative Authors
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
you may not use this file except in compliance with the License.
|
|
You may obtain a copy of the License at
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
See the License for the specific language governing permissions and
|
|
limitations under the License.
|
|
*/
|
|
|
|
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"math"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
// Algorithm from https://stackoverflow.com/a/21854246
|
|
|
|
// Only primes less than or equal to N will be generated
|
|
func primes(N int) []int {
|
|
|
|
var x, y, n int
|
|
nsqrt := math.Sqrt(float64(N))
|
|
|
|
is_prime := make([]bool, N)
|
|
|
|
for x = 1; float64(x) <= nsqrt; x++ {
|
|
for y = 1; float64(y) <= nsqrt; y++ {
|
|
n = 4*(x*x) + y*y
|
|
if n <= N && (n%12 == 1 || n%12 == 5) {
|
|
is_prime[n] = !is_prime[n]
|
|
}
|
|
n = 3*(x*x) + y*y
|
|
if n <= N && n%12 == 7 {
|
|
is_prime[n] = !is_prime[n]
|
|
}
|
|
n = 3*(x*x) - y*y
|
|
if x > y && n <= N && n%12 == 11 {
|
|
is_prime[n] = !is_prime[n]
|
|
}
|
|
}
|
|
}
|
|
|
|
for n = 5; float64(n) <= nsqrt; n++ {
|
|
if is_prime[n] {
|
|
for y = n * n; y < N; y += n * n {
|
|
is_prime[y] = false
|
|
}
|
|
}
|
|
}
|
|
|
|
is_prime[2] = true
|
|
is_prime[3] = true
|
|
|
|
primes := make([]int, 0, 1270606)
|
|
for x = 0; x < len(is_prime)-1; x++ {
|
|
if is_prime[x] {
|
|
primes = append(primes, x)
|
|
}
|
|
}
|
|
|
|
// primes is now a slice that contains all primes numbers up to N
|
|
return primes
|
|
}
|
|
|
|
const primesPath = "/primes/"
|
|
|
|
func handler(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
param := r.URL.Path[len(primesPath):]
|
|
n, err := strconv.Atoi(param)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
} else {
|
|
w.WriteHeader(http.StatusOK)
|
|
p := primes(n)
|
|
json.NewEncoder(w).Encode(p[len(p)-1:])
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
http.HandleFunc(primesPath, handler)
|
|
http.ListenAndServe(":8080", nil)
|
|
}
|