a programming puzzle
Yesterday afternoon one of my friends came up with this programming puzzle:
To write an algorithm with the minimum no. of executions to calculate the Sum of all natural numbers from 1 to N, that are divisible by 4 or 7 ?Though the question looked very simple, it was really exciting to find the solution. Here is the pseudo code of what we think as a good solution :
I know there are many other smart solutions for this problem. If you, have one share it in the comments section.
- Initialize a=0, b=0, c=0, result=0
- Run a loop for i = 1 to (N/28)
- a = a + i
- Next value of i
- Run a loop for i = (N/28)+1 to (N/7)
- b = b + i
- Next value of i
- Run a loop for i = (N/7)+1 to (N/4)
- c = c + i
- Next value of i
- result = (4*(a+b+c)) + (7*(a+b)) - (28*a)
Labels: computer programming, programming puzzles
4 Comments:
gud one... trying to find te other way out than te one u specified...hmmm not even able to think... google had corrupted my mind big time!!!
@Dpak
Thank You!!!
I ll try to post more in the future to get your mind, back to form :-)
Just remembered today to solve this
1. Initialize sum=0;i and n;
2. get the value of n;
3. Run a loop from 4 to n;
4. check if value of (i mod 4=0) or (i mod 7=0)
5. sum=sum+i;
6. print sum
@Dpak
Simple and very clean!!!
We at first, did something similar to this and then thought the iteration in our algorithm runs N/4 times
Post a Comment
<< Home