If I want you to leave this page with only one sentence, it would be this: “The sooner you start coding, the deeper you get stuck.”
When you face a programming problem, just don’t start coding the first idea that comes to your mind. Move back and look at it. Think about it. Think about it hard because there are overwhelming chances that the first idea is not the best one. Even if it gives you a correct solution, it will probably require more effort, take more space and be less efficient.
The example I am giving you here might seem a little obvious but extend it to other problems and you will get my point.
Let us write a program to list all factors of a given integer n. I am coding the first idea I had. Here it is:
void printFactors(int n)
{
for(int i = 1; i <= n; ++i)
{
if ( n % i == 0)
cout << i << ", ";
}
}
Yes the solution is correct. And if you want the factors of a few small numbers, its fine too. But think about it. Our function does a hell lot of useless operations. It continues the loop till 'n' while no factor of 'n' can be greater than 'n/2' except for 'n' itself. So we can make 'i <= n/2' instead of 'i <= n' and then print n.
Now wait a minute… what if 'n' is odd? There is 50% chance that it is. If it is odd, we keep dividing it by numbers like 4, 6, 8, 10 and so on which is useless. So we can divide 'n' by 2 in the beginning and then know if we only need to divide it by odd numbers.
Well… it seems thats about it. But it is not. Let us assume n = 10. When i = 2, then dividing 10 by 2 gives no remainder and 2 is a factor. But the number we multiply 2 with i.e. 5, is also a factor right? So along with i, n/i is a factor too. If we run the loop with this to n/2, we get double entries for all the factors. So we reduce the upper limit of i from n/2 to the square root of n. Now let me code this for you.
void printFactors(int n)
{
int limit = sqrt( (float)n); //sqrt() needs a float, double or long double argument
int increment;
if(n % 2 == 0)
increment = 1;
else
increment = 2;
for(int i = 1; i <= limit; i+= increment)
{
if (n % i == 0)
cout << i << ", " << n/i << ", ";
}
cout << n;
}
To prove the improvement in efficiency, the first function took 40 seconds for 100 large numbers and the latter took only 1 second for the same. That is 40 times faster.
This solution took more effort and space but was much more efficient than the previous one. And it doesn't print the factors in order but that can be arranged. A good program design for a bigger problem which comes after thinking hard will very likely give you all the three advantages.
So lads, its better to think an hour and code an hour than to think a mintue and code ten hours. Coming up with a solution quicker doesn't necessarily make you better
Pingback: almenia maria