5
[Golang] Digit fifth powers - Problem 30 - Project Euler
source link: http://siongui.github.io/2018/05/06/go-digit-fifth-power-problem-30-project-euler/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Golang] Digit fifth powers - Problem 30 - Project Euler
May 06, 2018
Problem: [1]
Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 1^4 + 6^4 + 3^4 + 4^48208 = 8^4 + 2^4 + 0^4 + 8^49474 = 9^4 + 4^4 + 7^4 + 4^4As 1 = 1^4 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
Solution:
443839
package main import ( "fmt" "strconv" ) func IsFifthPowerEqual(n int) bool { s := strconv.Itoa(n) sum := 0 for _, digit := range s { d, err := strconv.Atoi(string(digit)) if err != nil { panic(err) } sum += d * d * d * d * d } if sum == n { return true } return false } func main() { d95 := 9 * 9 * 9 * 9 * 9 fmt.Println("9^5 =", d95) fmt.Println("max possible: 6 * 9^5 =", 6*d95) sum := 0 for i := 2; i < 6*d95; i++ { if IsFifthPowerEqual(i) { fmt.Println(i) sum += i } } fmt.Println("Sum:", sum) }
Result:
9^5 = 59049 max possible: 6 * 9^5 = 354294 4150 4151 54748 92727 93084 194979 Sum: 443839
Test on:
- Ubuntu Linux 17.10, Go 1.10.2
- Go Playground
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK