I have to write a function that takes two parameters x,y. y is the power and x is the number, I am not asking for you to write my homework for me, but can someone help me out here is what I have so far, it works if both the numbers are even. But... the odd numbers are the bitch. thanks, jake.
publicclass PowerUp
{
publicint Power(int x, int y)
{
if(y%2==0 && x%2==0)//if both numbers are even.
{
while(y!=1)
{
x=x*x;
y=y/2;
}
}
else//if they are both odd.
{
x=x*x;
}
return x;
}
publicstaticvoid main(String[] args)
{
PowerUp newP=new PowerUp();
System.out.println("This is the answer: "+newP.Power(8,4));
}
}
publicclass PowerUp
{
publicint Power(int x, int y)
{
int result = 1;
for (int i = 0; i < y; i++){
result = result * x;
}
return result;
}
publicstaticvoid main(String[] args)
{
PowerUp newP=new PowerUp();
System.out.println("This is the answer: "+newP.Power(8,4));
System.out.println("This is the answer: "+newP.Power(3,3));
}
}
I am not sure why you are determining whether the number is even or odd, as calculating the power would not require this.
x ^ y (x to the power of y) requires that you multiply x y number of times, adding the result to each new multiplication. I would suggest putting this in a for next loop or a while loop.