w3resource logo


Euler Project

Project Euler solution: Largest palindrome product

Secondary Nav

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

Result : 906609

Solution in multiple languages

Python

n = 0
for a in range(999, 100, -1):
    for b in range(a, 100, -1):
        x = a * b
        if x > n:
            s = str(a * b)
            if s == s[::-1]:
                n = a * b
print(n)

Ruby

#!/usr/bin/env ruby

class Integer
  def palindromic?
    d = self.to_s.split('')
    return d == d.reverse
  end
end

max = 0
(100..999).each do |a|
  (a..999).each do |b|
    p = a * b
    if p > max and p.palindromic?
      max = p
    end
  end
end
puts max

C

#include <stdio.h>

static int is_palindromic(unsigned int zn);

int main(void)
{
  unsigned int i, j, zmax = 0;
  for (i = 100; i <= 999; i++) {
    for (j = 100; j <= 999; j++) {
      unsigned int zp = i*j;
      if (is_palindromic(zp) && zp > zmax) {
        zmax = zp;
      }
    }
  }
  printf("%u\n", zmax);
  return 0;
}

int is_palindromic(unsigned int zn)
{
  unsigned int zrev = 0, zt = zn;

  while (zt) {
    zrev = 10*zrev + (zt % 10);
    zt /= 10;
  }
  return zrev == zn;
}

Go

package main

import (
    "strconv"
)

func check_Palindrome(input string) bool {
    for i := 0; i < len(input)/2; i++ {
        if input[i] != input[len(input)-1-i] {
            return false
        }
    }
    return true
}

func main() {
    max, mul := 0, 0
    for i := 100; i < 1000; i++ {
        for j := i; j < 1000; j++ {
            mul = i * j
            if check_Palindrome(strconv.Itoa(mul)) && mul > max {
                max = mul
            }
        }
    }
    println(max)
}


Join our Question Answer community to learn and share your programming knowledge.

Help the community:

PHP: Loop

JavaScript: Delete duplicates in an array

Oracle: Round the number