fork(4) download
  1. def number2digits(long n) {
  2. def result = []
  3. for(/**/; n > 0; n /= 10) {
  4. result.add(0, n % 10)
  5. }
  6. return (result) ? result : [0]
  7. }
  8. assert number2digits(123) == [1, 2, 3]
  9.  
  10. def digits2number(digits) {
  11. return digits.inject(0l) { a, b -> a*10 + b }
  12. }
  13. assert digits2number([1, 2, 3]) == 123
  14.  
  15. def createPalindrome(long palindromeBeginning, boolean doubleDigitInMiddle) {
  16. def palindromeBeginningDigits = number2digits(palindromeBeginning)
  17. def palindromeEndingDigits = palindromeBeginningDigits.reverse()
  18. if (!doubleDigitInMiddle) {
  19. palindromeEndingDigits = palindromeEndingDigits.tail()
  20. }
  21. return digits2number(palindromeBeginningDigits + palindromeEndingDigits)
  22. }
  23. assert createPalindrome(123, false) == 12321
  24. assert createPalindrome(123, true) == 123321
  25.  
  26. COUNTER = 0
  27.  
  28. def findNDigitsDivisorPair(long x, int N) {
  29. int MAX_DIVISOR = 10**N - 1
  30. int MIN_DIVISOR = 10**(N-1)
  31. int squareRoot = Math.sqrt(x)
  32. if (MIN_DIVISOR <= squareRoot && squareRoot <= MAX_DIVISOR) {
  33. int lowerDivisorBound = Math.max(x / MAX_DIVISOR as int, MIN_DIVISOR);
  34. for (int i = lowerDivisorBound; i <= squareRoot; ++i) {
  35. double quotient = (x as double) / i
  36. ++COUNTER
  37. //println "$x / $i = $quotient"
  38. if (quotient % 1 == 0) return [i, quotient as int]
  39. }
  40. }
  41. return null
  42. }
  43. assert findNDigitsDivisorPair(143, 2) == [11, 13]
  44.  
  45. def findBiggestDivisiblePalindrome(digitsCount) {
  46. for (int begin = 10**digitsCount - 1; begin >= 10**(digitsCount-1); --begin) {
  47. long palindrome = createPalindrome(begin, true)
  48. def solution = findNDigitsDivisorPair(palindrome, digitsCount)
  49. if (solution) {
  50. println "Number of checks = " + COUNTER
  51. println "$palindrome = ${solution[0]} * ${solution[1]}"
  52. return palindrome
  53. }
  54. }
  55. }
  56. //assert findBiggestDivisiblePalindrome(9) = 999996100001699999
  57.  
  58. def start = new Date().getTime()
  59. findBiggestDivisiblePalindrome(3)
  60. println "Execution time: ${new Date().getTime() - start} ms"
  61.  
Success #stdin #stdout 1.83s 332416KB
stdin
Standard input is empty
stdout
Number of checks = 2138
906609 = 913 * 993
Execution time: 179 ms