Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using iteration to work out powers

Tags:

java

iteration

I'm basically trying to rewrite math.pow, I have the following obviously I'm not getting the concept of returning values. What exactly am I doing wrong?

public static int power(int x, int n)
{
    if (n == 0) return 1;
    int i,total;
    for(i = 0; i < n-1 ;i++);
    {   
        total = (x * total);
    }
    return total;


}
like image 648
orange Avatar asked Dec 21 '22 04:12

orange


2 Answers

You need to initialize total to 1.

int total = 1;

You can just rewrite everything to:

public static int power(int x, int n)
{
    int total = 1;
    for(int i = 0; i < n; i++) // i can be declared here directly
    {   
        total = (x * total);
    }
    return total; // total remains 1 if n = 0   
}
like image 122
Tudor Avatar answered Jan 05 '23 23:01

Tudor


public static int power(int x, int n)
{
    int total = 1; // Initialized total to 1
    for(int i = 0; i < n; i++)
    {   
        total = x*total;
    }
    return total;


}
like image 21
eboix Avatar answered Jan 06 '23 01:01

eboix