Implementing the exponential function with basic arithmetic operations -
for purpose of exercise, have implement exponential function basic arithmetic operations. came this, x base of operations , y exponent:
function expaetb() { product=1; (i=0; i<y; i++) { product=product*x; } homecoming product; };
however, there more basic operations product=product*x;
. should somehow able insert instead for
loop multiply , pass result, can't find way without falling infinite loop.
in same way exponentiation repeated multiplication, multiplication repeated addition.
simply create another function mulaetb
you, , watch out things negative inputs.
you go 1 more level , define adding in terms of increment , decrement, may overkill.
see, example, next programme uses overkill method of addition:
#include <stdio.h> static unsigned int add together (unsigned int a, unsigned int b) { unsigned int result = a; while (b-- != 0) result++; homecoming result; } static unsigned int mul (unsigned int a, unsigned int b) { unsigned int result = 0; while (b-- != 0) result = add together (result, a); homecoming result; } static unsigned int pwr (unsigned int a, unsigned int b) { unsigned int result = 1; while (b-- != 0) result = mul (result, a); homecoming result; } int main (void) { int test[] = {0,5, 1,9, 2,4, 3,5, 7,2, -1}, *ip = test; while (*ip != -1) { printf ("%d + %d = %3d\n" , *ip, *(ip+1), add together (*ip, *(ip+1))); printf ("%d x %d = %3d\n" , *ip, *(ip+1), mul (*ip, *(ip+1))); printf ("%d ^ %d = %3d\n\n", *ip, *(ip+1), pwr (*ip, *(ip+1))); ip += 2; } homecoming 0; }
the output of programme shows calculations correct:
0 + 5 = 5 0 x 5 = 0 0 ^ 5 = 0 1 + 9 = 10 1 x 9 = 9 1 ^ 9 = 1 2 + 4 = 6 2 x 4 = 8 2 ^ 4 = 16 3 + 5 = 8 3 x 5 = 15 3 ^ 5 = 243 7 + 2 = 9 7 x 2 = 14 7 ^ 2 = 49
if must have in single function, it's simple matter of refactoring function phone call inline:
static unsigned int pwr (unsigned int a, unsigned int b) { unsigned int xres, xa, result = 1; // grab mutual cases, simplifies rest of function (a>1, b>0) if (b == 0) homecoming 1; if (a == 0) homecoming 0; if (a == 1) homecoming 1; // powerfulness repeated multiplication. result = a; while (--b != 0) { // multiplication repeated addition. xres = result; xa = a; while (--xa != 0) result = result + xres; } homecoming result; }
function exponential
No comments:
Post a Comment