c++functionfactorialexponentiation

(C++) Calculating [(1! / 1^1) + (2! / 2^2) + ... + (20! / 20^20)] with using subfunctions of factorial and power


#include <iostream>
using namespace std;

int power(int a, int b); // Subfunction to calculate a^b
int fact(int c); // Subfunction to calculate factorial

int main() {
    
    int x=0;
    
    for(int i=1 ; i<=20 ; i++)
    
    x+= fact(i) / power (i,i);  // needs to calculate like [(1! / 1^1) + (2! / 2^2) + (3! / 3^3) + ...... + (20! / 20^20) // assigned x and sum it with counter to calculate final result
    
    cout<<x;
    return 0;
}


int power(int a, int b) { // a^b subfunction
    
    unsigned long long int multip=1; // written the biggest type just in case (idk if i need it)
    
    for (int i=1; i<=b; i++) {
        
        multip*=a;
        
    }
    
    return multip;
}

int fact(int c) { // factorial subfunction
    
    unsigned long long int multip=1;
    
    for (int i=c ; i>=1 ; i--) {
        
        multip*=i;
        
    }
    
    return multip;
}

I tried to calculate [(1! / 1^1) + (2! / 2^2) + ... + (20! / 20^20)] but somewhy program didn't work at all. output

I'm sorry if the mistake is obvious I've been trying for long hours and can't think much right now. I will return to the replies with fresh head.Have a good day.


Solution

  • You have some serious problems with your types:

    int power(...);
    int fact(...);
    

    => this should be long long.

    In top of this, you are doing integer division, while you need floating point division:

    fact(i) / power (i,i);
    

    ... should be:

    ((double) fact(i)) / power (i,i);