Forum Discussion

6 Replies

  • The answer is 6190144.

    And here is my Ruby script to calculate the sum of all odd numbers:

    puts (1..4976).step(2).inject(0, :+)

  • !/usr/bin/perl

    
    

    $f5 = ((0xf+5)*0xf5)+5*0xf+(0xf5/0xf5);
    for ($f=0,$fS=1; $fS<$f5; $fS++){$f+=$fS++}
    print $f;
    

  • python for good measure:

    >>> sum = 0
    >>> for i in range(1, 4976, 2):
    ...     sum += i
    ...
    >>> print sum
    6190144
    
  • Hi Jason,

    Nice one, but I still prefer oneliners 😉

    >>> sum(range(1, 4976, 2))
    6190144
    
  • DANGIT @gilliek! :) I was trying to force a list comprehension yesterday but it was not having my += business. Thanks for expanding my toolkit with sum, that's handy. And simple, I love how readable python can be.

     

  • sum (1 -> x) = (x*(x+1))/2
    sum even (if x is even) (1 -> x) = (x/2*(x/2 +1)
    sum odd (1-> x) = (x*(x+1))/2 - (x/2*(x/2 +1))
     = x/2 * ((x+1) - (x/2 +1))
     = x/2 * (x - x/2)

    the tcl code is :

     

    % set x 4976
    4976
     to convert odd to next even number if number is odd
    %set x [expr {($x-1)/2*2+2}]
    4976
    %set result [expr {$x/2 * ($x - $x/2) }]
    6190144