2017-09-23 43 views
1

我想只使用除了要提高一些的權力,但它不工作提高一個數量的功率,它只是提出了比original.Here大一些是我的代碼:只用另外

private void ExpOperation() 
    { 
     result = 0; 
     num01 = Int32.Parse(inpu01.Text); 
     num02 = Int32.Parse(inpu02.Text); 
     int a = num02; 
     num02 = num01; 
     int i = 1; 


     while (i <= a) 
     { 
      result = SimpleMulti(num01,num02); 
      num01 = result; 
      i++; 
     } 
     result_Text.Text = result.ToString(); 
    } 
    private int SimpleMulti (int num1, int num2) 
    { 
     int c = 0; 
     int i = 1; 
     while (i <= num2) 
     { 
      c += num1; 
      i++; 
     } 
     return c; 
    } 
+1

你需要更好的命名約定,我不能根據你的代碼告訴你的指數是什麼 – Alander

回答

0
private int SimpleMulti (int x, int y) 
{ 
    int product = 0; //result of multiply 

    for (int i = 0; i<y; i++){ 
     product += x; 
    } 
    //multiplication is repeated addition of x, repeated y times 
    //the initial solution with a while loop looks correct 

    return product; 
} 

private int ExpOperation(int x, int exponent) 
{ 
    int result = 1; 

    if (exponent == 0) { 
     return result; //anything that powers to 0 is 1 
    } 
    else 
    { 
     for (int i = 0; i < exponent; i++){ 
      result = SimpleMulti(result, x); 
      //loop through exponent, multiply result by initial number, x 
      //e.g. 2^1 = 2, 2^2 = result of 2^1 x 2, 2^3 = result of 2^2 x 2 
     } 
    } 

    return result; 
} 

請記住,此方法不支持負指數,它處理除法,但不是使用SimpleMulti,而是可以爲SimpleDivide創建一個方法,該方法使用減法代替。其原理是一樣的

+2

請提供描述給你的答案。它將幫助他人理解您的解決方案如何工作。 – FCin

0

我不認爲這個問題是這個網站的主要原因很有關係,但我得到了一個解決方案:

public long ExpOperation(int a, int b) 
{ 
    long result = 0; 
    long temp = 0; 
    for (int i = 1; i <= b; i++) // Executes a full loop when we have successfully multiplied the base number "a" by itself 
    { 
     for (int j = 1; j <= a; j++) // Increase the result by itself for a times to multiply the result by itself 
      result += temp; 
     temp = result: 
    } 
    return result; 
} 
0

因爲X^Y = X * X^(y-1),它可以遞歸解決。由於有問題的SimpleMulti返回整數,我假設base和exponent都是非負整數。

private static int PowerWithAddition(int x, int y) 
{ 
    if(y == 0){ 
     return 1; 
    } 

    var y1 = PowerWithAddition(x, y - 1); 
    var sum = 0; 
    for (int i = 0; i < y1; i++) 
    { 
     sum += x; 
    } 

    return sum; 
}