Problem 4 "Largest palindrome product"

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.

問 4 「最大の回文積」

左右どちらから読んでも同じ値になる数を回文数という. 2桁の数の積で表される回文数のうち, 最大のものは 9009 = 91 × 99 である.

では, 3桁の数の積で表される回文数の最大値を求めよ.

fn is_palindrome(a: u32) -> bool {
    let mut t = a;
    let mut b = 0u32;
    while t > 0 {
        b *= 10;
        b += t % 10;
        t /= 10;
    }
    a == b
}

fn update_largest_palindrome_product(lpp: &mut Option<u32>, with: u32) {
    match lpp.as_mut() {
        Some(v) => *v = with,
        None => *lpp = Some(with),
    }
}

fn scan_b(a: u32, largest_pp: &mut Option<u32>) {
    for b in (a..=999).rev() {
        let p = a * b;
        if p <= largest_pp.unwrap_or_default() {
            return;
        }
        if is_palindrome(p) {
            update_largest_palindrome_product(largest_pp, p);
        }
    }
}

fn main() {
    let mut largest_pal_pro: Option<u32> = None;
    for a in (110..=990).rev().step_by(11) {
        scan_b(a, &mut largest_pal_pro);
    }
    let ans = largest_pal_pro.unwrap();

    println!("{}", ans);
    assert_eq!(ans, 906609);
}
package main

import "fmt"

func isPalindrome(p int) bool {
	t := int(p)
	q := 0
	for t > 0 {
		q = q*10 + t%10
		t /= 10
	}
	return p == q
}

func scanB(a, lpp int) int {
	for b := 999; b >= a; b-- {
		p := a * b
		if p <= lpp {
			return lpp
		}
		if !isPalindrome(p) {
			continue
		}
		if p > lpp {
			lpp = p
		}
	}
	return lpp
}

func Example() {
	lpp := 0
	for a := 990; a >= 110; a -= 11 {
		lpp = scanB(a, lpp)
	}
	fmt.Println(lpp)
	// Output: 906609
}
→ Go playground
function assert(condition: any, msg?: string): asserts condition {
  if (!condition) {
    throw new Error(msg);
  }
}

function isPalindrome(p: number): boolean {
  let t = Number(p);
  let q = 0;
  while (t > 0) {
    q = q * 10 + t % 10;
    t = t / 10 | 0;
  }
  return p === q;
}

function scanB(a: number, lpp: number): number {
  for (let b = 999; b >= a; b--) {
    const p = a * b;
    if (p <= lpp) {
      return lpp;
    }
    if (isPalindrome(p)) {
      lpp = Math.max(lpp, p);
    }
  }
  return lpp;
}

let lpp = 0;
for (let a = 990; a >= 110; a -= 11) {
  lpp = scanB(a, lpp);
}
console.log(lpp);
assert(lpp === 906609);
→ TypeScript playground