Sum of the Digits in Numbers

From Software Engineers Wiki
Jump to: navigation, search

What is the sum of the digits of all the numbers from 1 to 2016?

Answer

Written in PHP.

function sum_of_digits($num)
{
        for ($sum = 0; $num > 0; $num /= 10)
                $sum += $num % 10;
        return $sum;
}

$first = 1;
$last = 2016;

for ($i = $first, $result = 0; $i <= $last; ++$i)
        $result += sum_of_digits($i);

print "Result is $result";
Personal tools
Namespaces

Variants
Actions
Navigation
Toolbox