0

I want to input very large numbers in C.And I also want to calculate the sum of its digits.Is there a way to input very large numbers?

Here is my Code.

#include<stdio.h>
main() {
    int sum=0,rem;
    int a;
    printf("Enter a number:-");
    scanf("%d",a);
}
jforberg
  • 6,537
  • 3
  • 29
  • 47

3 Answers3

0

Maximum type in ANSI C C99 is long long int for ints. There's no way to directly work with 200 digits numbers in C, unless you treat it as char * and work on it about.

Sorry but the basic code snippet you show & the objective you'll want to reach are really very far away one of the other...If you concrete a little more what kind of calculation you want perhaps can give you a hand about.

DvTr
  • 347
  • 1
  • 5
  • Ah..really..? Actually I want to get the sum of the digits of a large number..Is there a simple way to get it? – Gayantha Akalanka Oct 09 '16 at 12:50
  • Of course: as told, you can for example scanf("%d",&a) and sum it until EOF reached, or another way will be pick up all numbers in a pointer to memory and then begin to sum all of them. – DvTr Oct 09 '16 at 12:55
  • 3
    @GayanthaAkalanka "I want to get the sum of the digits of a large number" - That *very* important detail belongs in your question; not buried in a comment down here. if that is the *only* goal (sum digits) then you don't need a big number library. All you need do is read chars one at a time, and so long as they're digit chars, translate them to `int` from `0..9` and tally them to a running summation. Update your question *and* its title. – WhozCraig Oct 09 '16 at 13:02
0

There are limits. Some compilers has just an integer with 64-bit, some with 128-bit. So you can't use these integer types.

You can try to use the GMP library. GMP supports on 64-bit builds integers with 2^37 bits.

DogeAmazed
  • 858
  • 11
  • 28
0

You probably don't want to load all those 200 digits into memory. When all you want to calculate is the sum of the digits, then all you need during your program is some accumulator variable storing the sum of the digits so far. The type of this variable can be int, because 200 * 9 <= INT_MAX will always be true in conforming implementations of C.

#include <stdio.h>

int main(void) {
    int accumulator = 0;
    int read_result;

    printf("Enter a number:-");

    while (1) {
        read_result = fgetc(stdin);

        if ('0' <= read_result && read_result <= '9') {
            accumulator += read_result - '0';
        } else {
            break;
        }
    }

    printf("The sum of the digits is %d", accumulator);

    return 0;
}