Reputation: 13
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
Upvotes: 1
Views: 147
Reputation: 3247
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;
}
Example of pow that takes n
, k
while storing result in str
and returns how big in length
:
void pow(int n, int k, char* str, int* length)
{
int i, j, carry, temp;
str[0] = '1';
*length = 1;
for (i = 0; i < k; i++)
{
carry = 0;
for (j = 0; j < *length; j++)
{
temp = (str[j] - '0') * n + carry;
str[j] = temp % 10 + '0';
carry = temp / 10;
}
while (carry)
{
str[*length] = carry % 10 + '0';
carry /= 10;
(*length)++;
}
}
// reverse
for (i = 0; i < *length / 2; i++)
{
temp = str[i];
str[i] = str[*length - i - 1];
str[*length - i - 1] = temp;
}
str[*length] = '\0';
}
int main()
{
int n, k;
scanf("%d %d", &n, &k);
char str[100000];
int length;
pow(n, k, str, &length);
printf("%s", str);
return 0;
}
Upvotes: 0
Reputation: 64682
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;
}
Upvotes: 1