Project Euler 004–JavaScript

25 02 2011

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;

 

<head>

    <title>Project Euler 004</title>

</head>

<body >

    <script type="text/javascript">

 

        function IsPalindrome(number)

        {

            numberStr = number.toString();

            // simple palindrome test

            // we only have to go through the first

            // half of the letters

            for (c = 0; c < numberStr.length-c; c++)

            {

                if (numberStr[c] !=

                    numberStr[numberStr.length-c-1]) {

                    return false;

                }

            }

            return true;

        }

 

        answer = 0

        //here’s a familiar loop

        for(i = 100; i < 1000; i++)

        {

            for(j = i; j < 1000; j++)

            {

                product = i*j;

                if ((product > answer)

                && IsPalindrome(product))

                { answer = product; }

            }

        }

 

        document.write("<b>" + answer + "</b>");

    </script>

</body>

</html>

 

 

Discussion

Nothing too special here, but this is the one solution that didn’t use some sort of built in “reverse” function.  Still works.  Smile

If you have questions, leave a comment or please find me on Twitter (@azzlsoft) or email (rich@azzlsoft.com).

Advertisements

Actions

Information

2 responses

9 06 2011
Talbot benoit

for (c = 0; c < numberStr.length – c; c++)

is not valid.. error

9 06 2011
Rich

Talbot, thanks for finding that. Try retyping the line in question. It appears as though the “-” (hyphen/minus) has been turned into a “–” (en dash) by Windows Live Writer. It’s a very subtle difference.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: