Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Improving C++ code efficiency for a beginner (with example)

so I’m solving an exercise using C++ and the website I’m using keeps telling me my solution isn’t efficient enough. The code is 6 goddamn lines.

int multiples(int a, int b, int c) {
    int count{};
    for (int i = a; i <= b; i++) {
        if (i % c == 0)
            count++;
    }
    return count;
}

It’s supposed to find all the multiples of c within the interval of [a,b]. For example, a = 10 b = 27 c = 5 will find the numbers 10, 15, 20, 25 and return 4.

Maybe I could cut down on the range the for loop is covering? I’ve been staring at it for a solid 20 minutes now and I have no idea.
Some general advice on how to make code more efficient would be very appreciated too. Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You make the code more efficient by rewriting it from scratch. The approach in the question was flawed from the start. Efficiency is not so much gained by tweaking code, but by choosing the right algorithm.

Do the maths first. There are (b-a)/c; numbers in the interval [a,b] that are divisible by c. I might be off by one or two, I leave it to you to correct that.

int multiples(int a, int b, int c) {
    return (b-a)/c;
}

I suggest you to take pen and paper to try some cases. Try one where a%c == 0 && b%c != 0, one where a%c != 0 && b%c == 0, a%c == 0 && b%c == 0, and a%c != 0 && b%c != 0. Only then you get the full picture and know what code to write.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading