Hello I'm begginer in C++, and I need to make a program to calculate this equation. Can anybody help me? A and M reads from the keyboard
Equation: https://postimg.cc/WFbsFhF3
I try this code:
1 2 3 4 5 6 7 8 9 10 11 12
int M=1;
int A;
cin>>A;
cin>>M;
float sum;
for(int i = 1; i<=M; k++){
k = k*i;
float A1 = pow(A, k);
sum = A1 / k;}
You need a factorial function. The stuff in the loop is: pow(A, k) / factorial(k)
That will overflow the max value of float (or double) sooner than necessary. It's much more accurate and efficient to compute each term from the previous one:
T_{0} = 1, T_{i+1} = T_{i}*(A/k)
You just have to be sure to start with a sum that's 1 and then loop for k=1 to M instead of k=0 to M.
if k is small you can just do a simple loop where you grow factorial running every loop iteration and same for the power, each loop increase a running power, and divide it and add. If the numbers can go out of range (and they will very quickly) you need to do something smarter. say K is 4. 1!,2!,3! are normal and then 4! is actually 3! ( 4^4/3!*4 = 4^3/3! right?) and so on. note that for 4, you can also divide top and bottom by 2, and so on... so some sort of ongoing fraction reduction strategy will let you run it out farther. If you need more than that, you will need to study it deeper.