I have an input.txt file:
- First line:
m
and on the followingm
lines I have pairs of 2 numbersa
andn
I have to calculate a^n and the result can have max 10^8 digits. I made the program using arrays and giving values to a
and n
. It returned the correct answer. But what I have to do is to read the information from the file, calculate a^n and write the numbers in an output.txt file.
Example:
In input.txt I have on the first line
2
2 10
1 100000
output.txt
1024
1
As I said, the program works with any numbers wrote by me in the main program. Now I need help to extract the numbers from input.txt, put them in array and after I calculate them to return them in output.txt.
Non-compiling code copied from codepad.org
#include <stdio.h>
#include <stdlib.h>
const int MAX_NR_DIGITS = 10000;
void longNumClone(char *from, char *to)
{
int i;
for (i = 0; i < MAX_NR_DIGITS; i++)
to[i] = from[i];
}
void longNumPrint(char *num, int sizeNum) {
int i;
for (i = sizeNum-1; i >= 0; i--) {
printf("%i", num[i]);
}
}
int longNumDiv2(char *rez, char *num, int sizeNum) {
int i;
num[sizeNum] = 0;
rez[sizeNum] = 0;
for (i = sizeNum - 1; i >= 0; i--) {
rez[i] = ((num[i+1] - rez[i+1]*2) * 10 + num[i]) / 2;
}
if (rez[sizeNum - 1] == 0) {
return sizeNum - 1;
}
return sizeNum;
}
int multiply(char *rez, char *a, int sizeA, char *b, int sizeB) {
int sizeRez = 0, i;
for (i = 0; i < MAX_NR_DIGITS; i++) {
rez[i] = 0;
}
int temp = 0, j;
for (i = 0; i < sizeB; i++) {
for (j = 0; j < sizeA; j++) {
temp = b[i] * a[j];
int inc = 0;
do {
temp = temp + rez[i + j + inc];
rez[i + j + inc] = temp % 10;
if (i + j + inc + 1 > sizeRez) {
sizeRez = i + j + inc + 1;
}
temp = temp / 10;
inc++;
}while (temp != 0);
}
}
return sizeRez;
}
int superpow(char *rez, char *base, int sizeBase, char *exp, int sizeExp) {
int i;
char temp[MAX_NR_DIGITS];
char temp1[MAX_NR_DIGITS];
char temp2[MAX_NR_DIGITS];
for (i = 0; i < MAX_NR_DIGITS; i++) {
rez[i] = 0;
}
int sizeRez = 1;
rez[0] = 1;
while (sizeExp > 0) {
if (exp[0] & 1) {
longNumClone(rez, temp);
sizeRez = multiply(rez, temp, sizeRez, base, sizeBase);
}
longNumClone(exp, temp);
sizeExp = longNumDiv2(exp, temp, sizeExp);
longNumClone(base, temp1);
longNumClone(base, temp2);
sizeBase = multiply(base, temp1, sizeBase, temp2, sizeBase);
}
return sizeRez;
}
int main() {
// 4437053125^625
char a[MAX_NR_DIGITS] = {5, 2, 1, 3, 5, 0, 7, 3, 4, 4};
int sizeA = 10;
char n[MAX_NR_DIGITS] = {5, 2, 6};
int sizeN = 3;
char rez[MAX_NR_DIGITS];
int sizeRez = 0;
sizeRez = superpow(rez, a, sizeA, n, sizeN);
longNumPrint(rez, sizeRez);
return 0;
}
The arrays in main()
are deemed variable-length arrays (VLAs) because MAX_NR_DIGITS
is not deemed to be an integer constant expression, and you can't initialize VLAs. It would be OK in C++, but not in C.