Search code examples
c++performancenumbers

Finding the most divisible number in a 100,000 range


I'm a student in the 10th grade and our teacher assigned some exercises. I'm pretty advanced in my class but one exercise is just isn't coming together as I want. The exercise is as follows:

Given the numbers between 100,000 and 200,000, find the number with the most divisors (as in which number can be divided with the most numbers, any number).

I wrote something but it executes in 32 seconds(!) and I just can't figure out the logic behind it (I can't even check if the answer is correct).

This is the code that I wrote:

void f3() {
    int mostcount = 0, most, divisors = 0;
    for (int i = 100000; i <= 200000; i++) {
        for (int j = 1; j<=i/2; j++) {
            if (i % j == 0) {
                divisors++;
            }
        }
        if (divisors > mostcount) {
            mostcount = divisors;
            most = i;
        }
        divisors = 0;
    }
    cout << most << endl;
    return;
}

The output:

166320

Edit: My question is how can I reduce the runtime?

I'd be really thankful if you could explain your answer if you do decide to help, instead of just saying that I could do this with an XYZ type binary tree.


Solution

  • Using @AhmedAEK 's response:

    replace j<=i/2 with j<=sqrt(i), you only need to loop up to that, also #include <math.h> at the top, you also need to multiply the total divisors by 2, since there is a number above the sqrt that reflects the number below the sqrt. ie: 1000 is 10 x 100.

    void f3() {
        int mostcount = 0, most, divisors = 0;
        for (int i = 100000; i <= 200000; i++) {
            for (int j = 2; j<=sqrt(i); j++) {
                if (i % j == 0) {
                    divisors++;
                }
            }
            if (divisors > mostcount) {
                mostcount = divisors;
                most = i;
            }
            divisors = 0;
        }
        cout << most << endl;
        return;
    }