mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-24 23:04:42 +01:00
45: triangular pentagonal
This commit is contained in:
@@ -7,7 +7,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
for i := 7654321; i > 1; i-- {
|
for i := 7654321; i >= 2143; i -= 2 {
|
||||||
if !isPandigital(strconv.Itoa(i)) {
|
if !isPandigital(strconv.Itoa(i)) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,6 @@ func isPrime(n int) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
res := n
|
res := n
|
||||||
//牛顿法求平方根
|
|
||||||
for res*res > n {
|
for res*res > n {
|
||||||
res = (res + n/res) / 2
|
res = (res + n/res) / 2
|
||||||
}
|
}
|
||||||
|
|||||||
43
45_triangular_pentagonal_hexagonal/main.go
Normal file
43
45_triangular_pentagonal_hexagonal/main.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
i := 144
|
||||||
|
for {
|
||||||
|
m := 2*i*i - i
|
||||||
|
fmt.Println("i,m", i, m)
|
||||||
|
if isPentagonalNumber(m) {
|
||||||
|
fmt.Println("num:", m)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func isPentagonalNumber(n int) bool {
|
||||||
|
r := math.Sqrt(float64(1 + 24*n))
|
||||||
|
if r-float64(int(r)) != 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return int(r)%6 == 5
|
||||||
|
}
|
||||||
|
|
||||||
|
func isTriangleNumber(n int) bool {
|
||||||
|
//tn = ½n(n+1)
|
||||||
|
x := 2 * n
|
||||||
|
res := x
|
||||||
|
//牛顿法求平方根
|
||||||
|
for res*res > x {
|
||||||
|
res = (res + x/res) / 2
|
||||||
|
}
|
||||||
|
for i := res; i > 0; i-- {
|
||||||
|
if i*(i+1) == x {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user