Jan_K wrote: > On Sat, 01 Apr 2006 02:03:13 GMT, "Dave Burt" <dave / burt.id.au> wrote: > > Crap, I knew I should have fully tested my code. > > <snip> > > >> if input%4 == 0 || input%400 == 0 && input%100 != 0 > > > >Here's the mistake. > > > >1984 and 2004 are leap years. OK. > >1800 and 1900 are not leap years. Not OK - this program lists them as leap > >years. > >1600 and 2000 are leap years. OK. > > > >In case this info helps, && binds more closely than ||, so what you've got > >is the same as: > > > >if input%4 == 0 || (input%400 == 0 && input%100 != 0) > > > >You should be able to rearrange it to give the correct result for the 1984, > >2004, 1800, 1900, 1600 and 2000. > > Yep. > > if input%100 != 0 && input%4 == 0 || input%400 == 0 > > > Fix: > > ------------------------------------------------------------------------------- > puts 'Please enter the starting year' > input = gets.chomp > puts 'Please enter the ending year' > input2 = gets.chomp > puts > puts 'The following are leap years:' > > input = input.to_i > > while input <= input2.to_i > if input%100 != 0 && input%4 == 0 || input%400 == 0 > puts input.to_s > end > input = input + 1 > end > ------------------------------------------------------------------------------- > > > 1 line shorter at the expense of readability and performance: > > ------------------------------------------------------------------------------- > puts 'Please enter the starting year' > input = gets.chomp > puts 'Please enter the ending year' > input2 = gets.chomp > puts > puts 'The following are leap years:' > > while input.to_i <= input2.to_i > if input.to_i%100 != 0 && input.to_i%4 == 0 || input.to_i%400 == 0 > puts input.to_s > end > input = input.to_i + 1 > end > ------------------------------------------------------------------------------- > > I actually did a little benchmark calculating all the leap years for > the next 100 million years (with output going to nul). > > Results: > > 13:26 minutes for the first one. > 14:56 minutes for the second one. > > The shorter code was 11.16% slower. ------------------------------------------------------------------------------- puts 'Please enter the starting year' input = gets.chomp.to_i # Convert to Integer puts 'Please enter the ending year' input2 = gets.chomp.to_i # Convert to Integer puts puts 'The following are leap years:' while input <= input2 if inputi % 100 != 0 && input % 4 == 0 || input % 400 == 0 puts input.to_s end input = input + 1 end