find first 1500 natural numbers whose factors are either ONLY 2, 3, or 5

One way to think about the problem is to say take the number x and pass it through filters (you actually began doing this in your code). The first filter would say “while the number is divisible by 2 keep dividing it by 2”. The second filter would say the same thing for 3 and the third would say the same thing for 5. At the end you check to see if what you have left is equal to 1. If it is, it had no more factors. Here’s some pseudo code to help out:

function isDivisible(t) {
    while (t % 2 == 0) {
        t = t / 2;
    }
    while (t % 3 == 0) {
        t = t / 3;
    }
    while (t % 5 == 0) {
        t = t / 5;
    }
    return t == 1;
}

It’s probably worth noting that this is by no means the fastest way to approach this problem; there are much faster solutions.

Leave a Comment