Last active
January 9, 2016 03:06
-
-
Save ghthor/2660f11af7d801b3a7eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Go solution to https://projecteuler.net/problem=40 | |
| package main | |
| import ( | |
| "fmt" | |
| "log" | |
| "strconv" | |
| ) | |
| func main() { | |
| n := 1 | |
| b := make([]byte, 0, 1000000) | |
| for len(b) < 1000000 { | |
| b = append(b, []byte(fmt.Sprint(n))...) | |
| n++ | |
| } | |
| fmt.Println(n) | |
| product := 1 | |
| for i := 0; i <= 1000000; i = ((i + 1) * 10) - 1 { | |
| n, err := strconv.Atoi(string(b[i])) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| product *= n | |
| } | |
| fmt.Println(product) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| var str = "" | |
| var len = str.characters.count | |
| var n = 1 | |
| while len < 1000000 { | |
| let nStr = String(n) | |
| len += nStr.characters.count | |
| str += nStr | |
| n++ | |
| } | |
| print(n) | |
| struct Product { | |
| let result: Int | |
| let index: Int | |
| func addDigit(digit: String) -> Product { | |
| guard let d = Int(digit) else { | |
| return self | |
| } | |
| return Product(result: result * d, index: ((index + 1) * 10) - 1) | |
| } | |
| } | |
| let product = str.characters | |
| .enumerate() | |
| .reduce(Product(result: 1, index: 0)) { (product, char) in | |
| if (char.index + 1) % (product.index + 1) == 0 { | |
| return product.addDigit(String(char.element)) | |
| } | |
| return product | |
| } | |
| print(product.result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment