Find sum of digits of very large number.

How to find sum of digits of very large number?
ALCATRAZ1 - SUM OF DIGITS

think of the addition problems that you have done in your primary classes.
take input of numbers as strings and you try you’ll get it

C++

The limit of long long int is ~10^19. If you number is bigger than that, take the input as a string, add individual characters.

Python :

You have no limit on length of integer.

Java

Use BigInteger

@rashedcs You can use either Big integer(for using big integers in c++ you can use boost library) or can take input in string and then perform addition.

Implementation using C++ boost library (link) and using char array to store the number (link).

if you have to find the sum of n natural digits then simply the formula n*(n+1)/2 is applicable.

Use Big Integer in Java or take the input number as strings and perform addition of individual strings.

USE LONG INT OR LONG FLOATING POINTS in C++

C++ users use String to store the digits … then traversal of string is equivalent to traversal of each digit…

Try this problem to get the hold of it:

You can store the number in a string and calculate the sum of digits by reading one character at a time.

string s;

cin>>s;

long long x=0;

for(int i=0;i<s.length();i++)

x+=(int)s[i]-‘0’;

cout<<x;

in string you can store 10^64-1 digits

2 Likes

if size is 10^50 the how to solve this…

@rashedcs I’ve added implementations using both the approaches mentioned.

@rashedcs I have added the implementation of both approaches, you can check them to solve the question.

If size is 10^50…then???

@rashedcs both Biginteger and string approach will work without any problem.