Search code examples
c++numbersexponential

How to calculate and print 3^9999 in c++?


can someone explain how to let operations like 3^9999 work in c++, as i found, if number is too long it causes problems. I've heard that there is a way to work it out. (Please do not suggest any external libraries)


Solution

  • Hope you're not looking for optimisation...

    int N = 9998;
    int M = 5000;
    int arr [M];
    
    for ( int j = 0 ; j < M ; ++j )
            arr[j]=0;
    
    arr[M-1] = 3;
    
    
    for ( int i = 0 ; i < N ; ++i ) {
    
            for ( int j = 0 ; j < M ; ++j )
                    arr[j] = arr[j]*3;
    
            for ( int j = M-1 ; j > 0 ; --j ) {
                    arr[j-1] = arr[j-1] + arr[j]/10;
                    arr[j] = arr[j]% 10;
            }
    }
    
    
    for ( int j = 0 ; j < M ; ++j )
            std::cout << arr[j];