sum_of_digits_from_one_to_one_million.c

Aug 11th, 2020 (edited)
142
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. /*
2.
3.     sum_of_digits_from_one_to_one_million.c
4.
5.     Calculate total sum of digits of the numbers from 1 to 1000000.
6.     Number 1000000 is not included.
7.
11.
12.     https://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/
13.
14.     Mathematic solutions:
15.     https://www.xarg.org/puzzle/misc/sum-of-digit-sums-between-one-and-a-million/
16.     https://www.glassdoor.com/Interview/What-is-the-sum-of-the-digits-of-all-the-numbers-from-1-to-1000000-This-is-different-from-the-sum-of-the-numbers-For-inst-QTN_262688.htm
17.
18.     Further elaboration of the task:
19.     How many positive integers less than 1,000,000 have the sum of their digits equal to 19?
21.
22.
23.     You can find all my C programs at Dragan Milicev's pastebin:
24.
25.     https://pastebin.com/u/dmilicev
26.
27. */
28.
29. #include <stdio.h>
30.
31. // adds the digits of one number
32. int sum_of_the_digits_of_the_number( long number )
33. {
34.     int digit, sum_of_digits=0; // the sum of the digits of one number
35.     long mem=number;
36.
37.     while( number != 0 )
38.     {
39.         digit = number % 10;
40.         sum_of_digits += digit;
41.         number = number / 10;
42.     }
43.
44.     //printf("\n number = %6ld , sum_of_digits = %2d , ", mem, sum_of_digits );
45.
46.     return( sum_of_digits );
47.
48. } // sum_of_the_digits_of_the_number()
49.
50.
51. int main(void)
52. {
53.     long number;            // our number
54.     long max_number=1000000;// we add the digits of the numbers from 1 to max_number
55.     long total_sum=0;       // the total sum of the digits of all numbers
56.
57.     for( number=1; number<max_number; number++ )
58.     {
59.         total_sum += sum_of_the_digits_of_the_number(number);
60.         //printf(" total_sum = %6ld \n", total_sum );
61.     }
62.
63.     printf("\n Total sum of digits of the numbers from 1 to %6ld is %ld \n", max_number, total_sum );
64.
65.
66.     return 0;
67.
68. } // main()
69.
RAW Paste Data Copied