Hello,

i need your help.

I need to make a program which will make sum of digits in number e.g. 123 is 6
BUT, the number could be very big like 1000 digits long or more.(e.g. 1 005 854 684......) - of course without spaces
So, i cannot use datatypes like unsigned long long int, because of it is not enough.
Well, my idea is to store a number into string, then i have to make calculations to make sum of digits.

So, my question is: Is it better to use string (char array) or Int array? Do i need to convert char array to some number only array?

Thanks in advance for any help.

Dani AI

Generated

— nice and simple approach; treating the input as text and adding digit values is the right idea. 's note about GMP is correct when full big-integer arithmetic is required, but for the single task "sum the digits" a bignum library is overkill. Two practical improvements: process the input as a stream (no need to hold the whole number in memory) and pick an accumulator wide enough to avoid overflow on extremely long inputs.

A compact, robust C pattern that streams from stdin and skips non-digits:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    int c;
    uint64_t sum = 0;
    while ((c = getchar()) != EOF) {
        if (c >= '0' && c <= '9')
            sum += (uint64_t)(c - '0');
    }
    printf("%llu\n", (unsigned long long)sum);
    return 0;
}

A short Python alternative that does the same in one expression:

import sys
print(sum(int(ch) for ch in sys.stdin.read() if ch.isdigit()))

Notes and tips: ignore common separators (spaces, newlines, commas) or reject input with unexpected characters depending on the use case; prefer uint64_t unless expecting more than ~2.0e18 digits (practically never); a signed 32-bit accumulator can overflow if the number has more than floor(2,147,483,647/9) ≈ 238,609,294 digits. Use streaming to keep memory constant-time and simple validation to catch malformed input.

Recommended Answers

All 4 Replies

Thank you for answer. It looks good, but prgram wil run on different machines. I cannot install aditional library to every machine.

I don't want to upset you but this library is a C library and compiled into the executable. All skill levels arrive here so take a moment to try the library and see what happens.

I solved it, thank you for help.

Herre is my peace of code:

 // convert (char *)string to numbers and make sum of digits
 int len = strlen(string);
 int count = 0;
 for (int i = 0;i < len ;i++)
    {
        count = count + string[i] - '0';
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.