I am trying to create exponential function with for loop. so if num1 is 10, and num2 is 2
for (i = 0; i < num1; i++)
sum = sum + num2;
for (i = 开发者_JAVA百科0; i < num2 ; i++)
sum2 = sum + sum2;
Repeated addition mimics multiplication.
Repeated multiplication mimics exponentiation.
Just make two loops, one inside another: the inner loop to mimic multiplication and the outer loop to mimic exponentioation.
EDIT: here's a recursive method. Transforming it into a couple loops shouldn't be too difficult. Tested on codepad.
#include <stdio.h>
int mul(int b, int e) {
if (e == 0) return 0;
if (e == 1) return b;
return b + mul(b, e - 1); /* additions only */
}
int expo(int b, int e) {
if (e == 0) return 1;
if (e == 1) return b;
return mul(b, expo(b, e-1));
}
int main(void) {
printf("3^0 is %d\n", expo(3, 0));
printf("3^1 is %d\n", expo(3, 1));
printf("3^2 is %d\n", expo(3, 2));
printf("3^3 is %d\n", expo(3, 3));
printf("3^4 is %d\n", expo(3, 4));
return 0;
}
If you don't like me using /, implement your FPU yourself.
Something like this?
double power(int x, int p){
if(p==0)
return 1.0;
double res = x;
for(int i=1 ; i<p ; ++i)
res += x;
return res;
}
long mul(long a, long b){
if(a==0 || b==0)
return 0;
long res = 0;
for(int i=0 ; i<a ; ++i){
res += b;
}
return res;
}
long fac(long x){
if(x==0)
return 1;
return mul(fac(x-1),x);
}
double exponential(int x, int c)
{
double res = 0.0;
for(int i=0; i<=c;++i)
res += power(x)/(double)fac(i);
return res;
}
Not tested, see http://en.wikipedia.org/wiki/Exponential_function for definition of formula.
精彩评论