简体   繁体   中英

JavaScript Algorithm Performance - Count the number of numbers in a range divisible by k

I created an algorithm for finding the number of numbers inside a range that are divisible by a third number k. I got this to work but in polynomial time instead of linear time

function divisibleCount(x, y, k) {
    var count = 0;
    for (var i = x; i <= y; i++) {
        if (i % k === 0) {
            count++;
        }
    return count;
}

The arguments are as follows

x: Start of range
y: End of range
K: Number is divisible by

The problem is definitely the for loop which makes this polynomial time.

I attempted to use

for (var i = x; i <= k; i += k)

but got the wrong answer.

Is there any way I can improve this?

O(1).

Something like this:

Math.floor((y-1) / k) - Math.floor((x-1) / k)

Explanation:

Math.floor((x-1) / k) is the number of numbers divisible by k before the interval.

Math.floor((y-1) / k) is the number of numbers divisible by k up to the end of the interval.

Should be right for positive numbers and k > 0. Hopefully ;)

Edit: I see, you want to include y in the range. Ok, then change to:

Math.floor(y / k) - Math.floor((x-1) / k)

Is this for an assignment? I feel a little guilty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM