Find the largest palindrome made from the product of two 3-digit numbers - Javascript

前端 未结 21 1504
感情败类
感情败类 2020-12-28 17:16

Can anyone tell me what\'s wrong with the code. Find the largest palindrome made from the product of two 3-digit numbers.

function largestPalind         


        
21条回答
  •  梦谈多话
    2020-12-28 17:23

    I think you can go for code given at this link http://www.mathblog.dk/project-euler-problem-4/

    As this save your CPU cycle from multiplication, which is quite costly operation.

    Well even in this you can make some more to make to make it more like, you can modify its while loop a bit

    while (!found) {
        firstHalf--;
        palin = makePalindrome(firstHalf);
        for (int i = 999; i > 99; i--) {
            if ((palin / i) > 999 || i*i < palin) {
                break;
            }
    
            if ((palin % i == 0)) {
                found = true;
                factors[0] = palin / i;
                factors[1] = i;
                break;
            }
        }
    }
    

    So here instead of moving from i=999 : 100, we can write it as i=sqrt(palin):100, as you can find factorial of number within its square root. Refer link How to find Number is prime number or not!

    And also you can change if(condition) to if(!(palin%i)) as comparing with zero is usually not considered a good practice also comparing takes more CPU cycle compared to your simple negating bits.

提交回复
热议问题