Skip to content

Instantly share code, notes, and snippets.

@jozsefs
Last active April 7, 2017 12:24
Show Gist options
  • Select an option

  • Save jozsefs/1a0b167a0563d9c4230f76bf9bd2c8d2 to your computer and use it in GitHub Desktop.

Select an option

Save jozsefs/1a0b167a0563d9c4230f76bf9bd2c8d2 to your computer and use it in GitHub Desktop.
biggest-prime-in-number.go
package main
import (
"fmt"
"math"
"strconv"
"log"
"sort"
"time"
"errors"
)
type Primes []uint64
func (a Primes ) Len() int { return len(a) }
func (a Primes ) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a Primes ) Less(i, j int) bool { return a[i] < a[j] }
func main() {
//var num uint64 = 1<<64 - 121 -> RIPs the play.golang.org
defer timeTrack(time.Now(), "main")
nums := [...]uint64{
5439804848980213812,
4444444444444444454,
0,
4,
9832197432987498198,
}
for _, num := range nums {
checkNumber(num)
}
}
func checkNumber(num uint64) {
res, err := getBiggestPrimeInNumber(num)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("In the number: %d\tthe biggest prime is: %d\n", num, res)
}
}
func isPrime(value uint64) bool {
var i uint64;
for i = 2; i <= uint64(math.Floor(math.Sqrt(float64(value)))); i++ {
if value % i == 0 {
return false
}
}
return value > 1
}
func getBiggestPrimeInNumber(num uint64) (res uint64, err error) {
defer timeTrack(time.Now(), "getBiggestPrimeInNumber")
if num < 2 {
log.Fatal("The number should be higher than 1")
}
var primes Primes
numStr := strconv.FormatUint(num, 10)
strLen := len(numStr)
for i := 0; i <= len(numStr); i++ {
primes = nil
for j := 0; j < i; j++ {
slice := numStr[j:strLen-(i-1)+j]
slicedNum, _ := strconv.ParseUint(slice, 10, 64)
if isPrime(slicedNum) {
primes = append(primes, slicedNum)
}
}
sort.Sort(primes)
if len(primes) > 0 {
return primes[len(primes) - 1], nil
}
}
return 0, errors.New("Prime has not been found")
}
func timeTrack(start time.Time, name string) {
elapsed := time.Since(start)
fmt.Printf("%s took %s\n", name, elapsed)
}
@ekkinox
Copy link
Copy Markdown

ekkinox commented Apr 7, 2017

Next step, use import os and os.Args[1] to make it as a cli :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment