This is the 13th day of my participation in the August More Text Challenge.More challenges in August

Topic link

263. Ugly number

Topic describes

Give you an integer n, please determine whether n is ugly. If so, return true; Otherwise, return false.

Ugly numbers are positive integers that contain only prime factors 2, 3, and/or 5.

Knock blackboard: ugly number, must be positive integer!! Then, there are integers that only contain a number of 2’s, 3’s and 5’s

The test case

Input: n = 6 Output: true Description: 6 = 2 x 3Copy the code

Tip:


2 31 < = n < = 2 31 1 -2^{31} <= n <= 2^{31 – 1}

Subject analysis

For a more popular description, if a number n is multiplied by several 2, 3, and 5, the mathematical expression is n = 2 * a + 3 * b + 5 * c, where a, b, and c >= 0

Then we can solve the problem by dividing 2 by n, then dividing 3 by n, then dividing 5 by 3…

So the simple idea is, now we need to figure out how to make sure that n goes into 2,3,5, and when it doesn’t go into it, we have to change the number. Let’s try 2,3,5, and see what’s left at the end

If you have 0 or 1 left, that means it’s all divided, that’s the ugly number we’re looking for; Otherwise, it’s not

Tries to answer

According to the problem analysis, write version 1 code

var isUgly = function(n) {
    if(n <= 0)return false;
    for (; n % 2= =0; n = n / 2) {}
    for (; n % 3= =0; n = n / 3) {}
    for (; n % 5= =0; n = n / 5) {}
    return n ==0||n==1 ? true : false;
};
Copy the code

Optimize the summary

How can I say, so-so, just three for loops sitting in rows looking a little bit annoying. Ugly numbers are prime numbers only 2, 3, 5. If there are more ugly numbers, there will be more for loops.

This optimization is easy, just change it to a prime array loop and call the for loop. Perfect ideas kill people

var isUgly = function(n) {
    if (n <= 0) return false;
    [2.3.5].forEach(m= > {
        for (; n % m == 0; n = n / m) {}
    })
    return n == 0 || n == 1 ? true : false;
};
Copy the code