Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- sum_of_digits_from_one_to_one_million.c
- Calculate total sum of digits of the numbers from 1 to 1000000.
- Number 1000000 is not included.
- Task from
- https://web.facebook.com/photo/?fbid=292086525221428&set=gm.3162235480538814
- https://web.facebook.com/anusha.sritharan.54
- https://www.geeksforgeeks.org/count-sum-of-digits-in-numbers-from-1-to-n/
- Mathematic solutions:
- https://www.xarg.org/puzzle/misc/sum-of-digit-sums-between-one-and-a-million/
- 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
- Further elaboration of the task:
- How many positive integers less than 1,000,000 have the sum of their digits equal to 19?
- https://www.slader.com/discussion/question/how-many-positive-integers-less-than-1000000-have-the-sum-of-their-digits-equal-to-19/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // adds the digits of one number
- int sum_of_the_digits_of_the_number( long number )
- {
- int digit, sum_of_digits=0; // the sum of the digits of one number
- long mem=number;
- while( number != 0 )
- {
- digit = number % 10;
- sum_of_digits += digit;
- number = number / 10;
- }
- //printf("\n number = %6ld , sum_of_digits = %2d , ", mem, sum_of_digits );
- return( sum_of_digits );
- } // sum_of_the_digits_of_the_number()
- int main(void)
- {
- long number; // our number
- long max_number=1000000;// we add the digits of the numbers from 1 to max_number
- long total_sum=0; // the total sum of the digits of all numbers
- for( number=1; number<max_number; number++ )
- {
- total_sum += sum_of_the_digits_of_the_number(number);
- //printf(" total_sum = %6ld \n", total_sum );
- }
- printf("\n Total sum of digits of the numbers from 1 to %6ld is %ld \n", max_number, total_sum );
- return 0;
- } // main()
Add Comment
Please, Sign In to add comment