Created
December 12, 2016 09:09
-
-
Save sbutkaliuk/9fb5021723eba7f6ec9835b0bf8d48b1 to your computer and use it in GitHub Desktop.
Palindrome
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
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func int10Pow(pow uint) uint { | |
return uint(math.Pow(10, float64(pow))) | |
} | |
// returns reversed uint number | |
func reverse(num uint) uint { | |
var res uint | |
for num != 0 { | |
res = res*10 + num%10 | |
num = num / 10 | |
} | |
return res | |
} | |
// returns palindrome number with specified left half | |
func construnctNumber(leftHalfNumber, pow uint) uint { | |
result := leftHalfNumber * int10Pow(pow) | |
return result + reverse(leftHalfNumber) | |
} | |
// returns palindrome and multipliers | |
func getPalindrome(pow uint) (uint, uint, uint) { | |
/// when powering n-digit 9-th (999, 9999) result is always (9...98|0...01). | |
// We will set first half of number to 9...97 | |
half := int10Pow(pow) - 3 | |
left, right := int10Pow(pow-1), int10Pow(pow)-1 | |
for { | |
constructed := construnctNumber(half, pow) | |
for j := left; j <= right; j++ { | |
if constructed%uint(j) == 0 { | |
del := uint(constructed / j) | |
if del >= left && del <= right { | |
return constructed, del, j | |
} | |
} | |
} | |
half-- | |
} | |
} | |
func main() { | |
var pow uint = 3 | |
palindrome, v1, v2 := getPalindrome(pow) | |
fmt.Printf("palindrome from multiplying 2 %v-digit numbers (%v,%v): %v\n", pow, v1, v2, palindrome) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment