How to optimise this programme that calculates 2^p

Viewed 113

I have limited p to 50,000 but would like to use this code for p > 1,000,000. To simplify the code the arrays are pre-defined, not created with malloc - which has already made it faster. I understand the problem is the calculations within the two loops, division and modulus really slow the code down. Removing zeros from the beginning of the final number and printing the final array do not seem to cause any problems.

#include <stdio.h>

unsigned int p, l, zero;

int main() {

int power2[50005] = { 0 };
int product[50005] = { 0 };
int carry[50005] = { 0 };
            
                printf("Enter power: ");
                scanf("%u", &p);
                l = (p * 0.4) + 1;
                
                power2[l-1] = 2;

            for (int j=p-2; j>-1; --j) {
            for (int i=l-1; i>-1; --i) {
                
                power2[i] *= 2;
                carry[i] = power2[i] / 10;
                
                product[i] = power2[i] + carry[i+1];
                
                carry[i] = product[i] / 10;
                product[i] %= 10;
                
                power2[i] = product[i];
                    
            }
            
        }
                /* remove 0s from beginning of final array - product[] */       
                zero = 0;
                while (product[zero] == 0) {
                    ++zero;
                } 
                for (int i=zero; i<l; ++i) {
                    printf("%d", product[i]);
                }

printf("\n");
return 0;
}
0 Answers
Related