2013-02-08 69 views
1

爲了練習的目的,我必須用最基本的算術運算來實現指數函數。我想出了這個,其中X是基礎和ÿ指數:用基本算術運算實現指數函數

function expAetB() { 
    product=1; 
    for (i=0; i<y; i++) 
    { 
      product=product*x; 
    } 
    return product; 
}; 

然而,還有比product=product*x;更基本的操作。我應該以某種方式能夠插入,而不是另一個for循環乘法和傳遞的結果,但我不能找到一種方式來做到這一點,而不陷入無限循環。

+0

這是我在這個網站上看到的最糟糕的標題之一。注意我是如何重寫你的頭銜的。 –

回答

2

以相同的方式,指數是重複的乘法,所以乘法就是簡單的重複加法。

簡單地創建另一個函數mulAetB它爲你做,並注意諸如負面投入的東西。

你甚至可以進一步級別並定義增量和減量,但這可能是矯枉過正。


見,例如,其使用另外的矯枉過正方法下面的程序:

#include <stdio.h> 

static unsigned int add (unsigned int a, unsigned int b) { 
    unsigned int result = a; 
    while (b-- != 0) result++; 
    return result; 
} 

static unsigned int mul (unsigned int a, unsigned int b) { 
    unsigned int result = 0; 
    while (b-- != 0) result = add (result, a); 
    return result; 
} 

static unsigned int pwr (unsigned int a, unsigned int b) { 
    unsigned int result = 1; 
    while (b-- != 0) result = mul (result, a); 
    return 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 (*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; 
    } 
    return 0; 
} 

該程序的輸出顯示計算是正確的:

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 

如果你真的必須它在一個單一的功能,這是一個簡單的問題重構函數調用是內聯:

static unsigned int pwr (unsigned int a, unsigned int b) { 
    unsigned int xres, xa, result = 1; 

    // Catch common cases, simplifies rest of function (a>1, b>0) 

    if (b == 0) return 1; 
    if (a == 0) return 0; 
    if (a == 1) return 1; 

    // Do power as repeated multiplication. 

    result = a; 
    while (--b != 0) { 
     // Do multiplication as repeated addition. 

     xres = result; 
     xa = a; 
     while (--xa != 0) 
      result = result + xres; 
    } 

    return result; 
} 
+0

好的,謝謝。但是創建第二個功能太快捷。理想情況下,我應該只使用一系列重疊的循環,並且不要使用諸如product = product * x的快捷方式; – user2052971

+0

@ user2052971,像你在前面的評論中所要求的那樣的問題難以置信地不可能幫助未來的訪問者(因而風險被關閉),僅僅因爲唯一的地方你會得到這樣的限制是在瘋狂的教育者心中。但我會盡全力做到這一點。 – paxdiablo

+0

感謝您的回答和評論,我真的很感激它,但是您錯了一件事......我認爲了解它的工作原理非常有趣,對我而言這是一個有趣的挑戰。顯然,我們假設能夠進行階乘甚至是減價,這對我來說似乎很了不起。所以我想有些人不僅希望代碼能夠工作,還想知道它是如何工作的。再次感謝! – user2052971