Compute sum of digits in all numbers from 1 to n | Returns sum of all digits in numbers from 1 to n ; initialize result ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program
< ? php function sumOfDigitsFrom1ToN ( $ n ) { $ result = 0 ; for ( $ x = 1 ; $ x <= $ n ; $ x ++ ) $ result += sumOfDigits ( $ x ) ; return $ result ; } function sumOfDigits ( $ x ) { $ sum = 0 ; while ( $ x != 0 ) { $ sum += $ x % 10 ; $ x = $ x / 10 ; } return $ sum ; } $ n = 328 ; echo " Sum ▁ of ▁ digits ▁ in ▁ numbers ▁ from " . " ▁ 1 ▁ to ▁ " . $ n . " ▁ is ▁ " . sumOfDigitsFrom1ToN ( $ n ) ; ? >