x power y - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

x power y

Posts: 6Member
how to get the result without using multiplication operator ?
Here is my code:
[code]
int i;
System.out.print("Enter base: ");
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
System.out.print("Enter power: ");
int num2 = sc.nextInt();

for(i=1;i<=num2;i++)
{
[color=Red]product=product*num1;[/color]
}

[/code]

• Posts: 17Member
Java does these calculations through the math class using its "pow()" function.

Define the variables. The calculation for the Math class needs two numbers - one for the base number and the other for the exponent. The following code defines two variables for use later in the code:
int myNumber = 3;
int myExponent = 5;

Create a variable to assign the return value of the calculation. This is used to provide a way to store the calculated total:
int myTotal;

Call the "pow()" method to calculate the total. The following syntax raises the variable value of 3 to the 5th power:
myTotal = Math.pow(myNumber, myExponent);

Print the results for display. To evaluate the total, use the following syntax to print to the console:
System.out.println(myTotal);

• Posts: 17Member

int myNumber = 3;
int myExponent = 5;
int myTotal;
System.out.print("Enter base: ");

Scanner sc = new Scanner(System.in);
myNumber = sc.nextInt();
System.out.print("Enter power: ");
myExponent = sc.nextInt();

myTotal = (int) Math.pow(myNumber, myExponent);

• Posts: 6Member
Thank you for the answer but i'm not required to use functions like pow()...I'm sorry for not saying it earlier..can you suggest another solution for this? thanks in advance...
• Posts: 17Member
What exactly are your requirements so I can help further.
can you use---

int a = math.exp(b); //(x^b)
• Posts: 6Member
I can't use math.exp(). I am required to write a program that will calculate x power y without using any math class functions and multiplication operator(*).I've already done X^2 by just using loops and addition. Do you think i can use that also in x power y? Here is my code in x^2:

[code]
int i;
int product=0;
System.out.print("Enter 1st num: ");
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
for(i=1;i<=num1;i++)
{
product=product+num1;
}