Created
April 17, 2017 16:23
-
-
Save ksexton/e451e6d16c5054ea0207b41dc7975817 to your computer and use it in GitHub Desktop.
Go Project Euler exercise
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
// Find a problem at projecteuler.net then create the solution. Add a | |
// comment beneath your solution that includes a description of the | |
// problem. Upload your solution to github. Tweet me a link to your | |
// solution. | |
// | |
// https://projecteuler.net/problem=4 | |
// A palindromic number reads the same both ways. The largest palindrome | |
// made from the product of two 2-digit numbers is 9009 = 91 × 99. | |
// | |
// Find the largest palindrome made from the product of two 3-digit | |
// numbers. | |
package main | |
import ( | |
"fmt" | |
"strconv" | |
) | |
func main() { | |
num1, num2, result := findPalindrome(100, 999) | |
fmt.Printf("%v * %v = %v, which is the largest palindrome!", num1, num2, result) | |
} | |
func findPalindrome(min, max int) (num1, num2, result int) { | |
var largestNumber1 int | |
var largestNumber2 int | |
var largestResult int | |
for num1 := min; num1 <= max; num1++ { | |
for num2 := min; num2 <= max; num2++ { | |
result := num1 * num2 | |
if isPalindrome(result) == true && result > largestResult { | |
largestResult = result | |
largestNumber1 = num1 | |
largestNumber2 = num2 | |
} | |
} | |
} | |
return largestNumber1, largestNumber2, largestResult | |
} | |
func isPalindrome(num int) bool { | |
s := strconv.Itoa(num) | |
for i := 0; i < len(s)/2; i++ { | |
first := s[0+i] | |
last := s[len(s)-(1+i)] | |
if first != last { | |
return false | |
} | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment