we had a meeting at 3:30 and three of us are waiting for 2 more people to join us. In between we are discussing about an interview question that I asked yesterday. What is the sun of all the 3 digit numbers that is divisible by 7? Sathish answered he can not do it with pen and paper but can do it as a Java program.
int sum = 0;
for(int i=100;i<1000;i++)
if(i % 7 == 0)
sum += i;
print(i)
Anish bettered the answer saying we don't need to do expensive division
and can do it using a while loop
int sum = 0;
int i = 105;
while(i<1000)
{
sum += i;
i += 7;
}
return i;
I don't like for loop and wanted a generic solution where the divisible number can be anything.
I don't want to change the code in case want to add all the 7 digit numbers divisible by 71. Or so on. Sathish's program can be tweaked a little to make it more generic, but that is not what we wanted. I wanted the expensive division operators out. And want to change while loops to for loops.
int getSum(int factor, int lowest, int highest) {
int start = ((lowest-1)/factor)+1)*factor;
int end = (highest/factor)*factor;
int sum = 0;
for(int i=start;i<=end;i+=factor){
sum += i;
}
return i;
}
Monday, 30 November 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment