Home > OS >  How to print a big number in character array-string
How to print a big number in character array-string

Time:11-21

The number n^k is entered, I need to output the value in a character array-string

I have no idea how to write the code

CodePudding user response:

Your problem does not seem well specified. You are not describing the problem or the limits in detail.

Regardless, here is some simple code to hopefully get you started.

#include <stdio.h>
#include <math.h>

int main(void) {
    int n;
    printf("Enter N:\n");
    scanf("%d", &n);
    
    int k;
    printf("Enter K:\n");
    scanf("%d", &k);
    
    int result = pow(n,k);
    char text[100];
    sprintf(text, "%d", result);
    
    printf("The Answer is %s\n", text);

    return 0;
}

CodePudding user response:

Implement your own pow that would work with big numbers.

int main()
{
    int n, k;
    scanf("%d%d", &n, &k);
    char* s = (char*)malloc(1000000);
    int i, j, len, temp, carry;
    s[0] = '1';
    len = 1;
    for (i = 1; i <= k; i  )
    {
        carry = 0;
        for (j = 0; j < len; j  )
        {
            temp = (s[j] - '0') * n   carry;
            s[j] = temp % 10   '0';
            carry = temp / 10;
        }
        while (carry > 0)
        {
            s[len] = carry % 10   '0';
            carry /= 10;
            len  ;
        }
    }
    for (i = len - 1; i >= 0; i--)
        printf("%c", s[i]);
    return 0;
}
  •  Tags:  
  • c
  • Related