# Project Euler #4

**URL:** <https://forum.kx.com/t/project-euler-4/12693>\
**Category:** Community Support\
**Tags:** kdb-and-q\
**Created:** [October 23, 2022, 8:15pm UTC](https://forum.kx.com/t/project-euler-4/12693 "2022-10-23T20:15:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![SJT1](https://avatars.discourse-cdn.com/v4/letter/s/eb8c5e/32.png) [@SJT1](https://forum.kx.com/u/SJT1)\
**Post date:** [October 23, 2022, 8:15pm UTC](https://forum.kx.com/t/project-euler-4/12693/1 "2022-10-23T20:15:00Z")

</div>

# 4. Largest palindromic product

&nbsp;

_We find the highest palindromic number in a list, and discover a general form for the last (or first) item that passes a test, without testing every item.&nbsp;_

## Problem

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.

## Solution

Our candidates are the products of the unique pairs of 3-digit numbers:

```
c:prdeachdistinctasceach{xcrossx}1\_til1000 / candidate productsip:{x~reversex} / is palindrome?maxcwhereipeachstringc

```

## Optimisation

Or we can loop through the products in descending order:

```
i:countC:asccwhile[notipstringCi-:1;] C i

```

The cost of the sort and the explicit loop is repaid by not casting the entire list to strings and testing all of them.

```
q)\tsmaxcwhereipeachstringc9424835552q)\tsi:countC:ascc;while[notipstringCi-:1;]; C i1012584304

```

A functional version of the above:

```
.[@] ({notipstringx y}.)@[;1;-1+]/(ascc;count[c]-1)

```

Note the use of `@[;1;-1+]/` to decrement the index, and `.[@]` to resolve the result.

## Generalisation

From this we can see a general form for finding the last item that passes a test:

```
lastitem:{[test;list].[@] ({x y z}[test].)@[;1;-1+]/(list;-1+countlist)}lastitem[notipstring@]ascc

```

From&nbsp;https://github.com/qbists/studyq/blob/main/euler/04.md

Studying q rocks.&nbsp;

---

<div class="post-metadata">

**Author:** ![LeahS1](https://avatars.discourse-cdn.com/v4/letter/l/3da27b/32.png) [@LeahS1](https://forum.kx.com/u/LeahS1)\
**Post date:** [October 26, 2022, 7:48pm UTC](https://forum.kx.com/t/project-euler-4/12693/2 "2022-10-26T19:48:00Z")

</div>

Brilliant post @SJT,&nbsp;

Great reference for our KX Community!&nbsp;
