只用另外

问题描述:

我想只使用除了要提高一些的权力,但它不工作提高一个数量的功率,它只是提出了比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

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

我不认为这个问题是这个网站的主要原因很有关系,但我得到了一个解决方案:

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; 
} 

因为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; 
}