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.
>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.