Trivial Code; Unexpected Output

I recently read an old post about a guy who taught himself how to write computer programs after failing at it a number of times before. Midway through the article he points to the kind of problem that really got him started on his path to learning:

My struggle to become a hacker finally saw a breakthrough late in my freshman year of college, when I stumbled on a simple question:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6, and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

What’s especially neat about it is that someone who has never programmed — someone who doesn’t even know what a program is — can learn to write code that solves this problem in less than three hours. I’ve seen it happen. All it takes is a little hunger. You just have to want the answer.

It took me about three minutes, not hours (see below). Then again, I first learned to program computers about thirty years ago. What held my interest in the article, and this question especially, was it got me to thinking how, if I were the teacher and using this example to teach somebody how to program, how I might extend the problem a little by asking the student to make the program more flexible — extend it to let the user input any two numbers (not just 3 and 5), and any ceiling value (not just 1000). That’s what I did in the trivial example below.

What I didn’t expect, however, were the outputs when I repeatedly ran the program with values of ceiling 10 times greater than the previous one (10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000). It’s not intuitive to me that each successive sum would be a little over 100 times greaterĀ (not exactly) than the previous one. Not 10 times greater, which might appeal to your intuition (but still wouldn’t be obvious to me).

I have an email in to my brainy friend on the east coast asking for an explanation. I was told by a another friend of ours he got a perfect score on the SAT.

public class Quiz {

public static void main(String [] args) {

int firstNumber;
firstNumber = Integer.parseInt(args[0]) ;

int secondNumber;
secondNumber = Integer.parseInt(args[1]) ;

int ceiling ;
ceiling = Integer.parseInt(args[2]) ;

long sum = 0 ;

for(int i=1; i<ceiling; i++) {

if( ( i%firstNumber ) == 0 || ( i%secondNumber ) == 0 ) {

sum += i ;

}

}

System.out.println( “Sum: ” + sum ) ;

}

}

————-Output————-

>java Quiz 3 5 10
Sum: 23

>java Quiz 3 5 100
Sum: 2318

>java Quiz 3 5 1000
Sum: 233168

>java Quiz 3 5 10000
Sum: 23331668

>java Quiz 3 5 100000
Sum: 2333316668

>java Quiz 3 5 1000000
Sum: 233333166668

>java Quiz 3 5 10000000
Sum: 23333331666668

>java Quiz 3 5 100000000
Sum: 2333333316666668