Find a number to the power of another number? - java

I am trying to write a function in java that finds the result of an operand raised to the power of another.
I can't use the pow function or any form of loop. What are any possible solutions? I tried "^" and that didn't work.
public static String raiseP(int op1, int op2){
int result = op1 ^ op2; //Doesn't Work
return result;
}
Would there be a way to do this using basic math?
I have written:
public static int pow(int x, int y, int n, int z){
if (y == n){
System.out.println(z);
return z;
}
else{
z = z*x;
n += 1;
pow(x,y,n,z);
return 0;
}
}
ex: pow(5,9,0,1) == 5^9
but am not allowed to use recursion.

Without being able to call Math.pow or using loops, the only other possibility is using recursion:
public int powerFunction(int base, int exponent) {
if(exponent < 0){ throw new IllegalArgumentException("unsupported negative pow"); }
if(exponent == 0){ return 1; }
else{
return base * powerFunction(base, exponent - 1);
}
}
Calling powerFunction(2, 3) will give you: 1 * 2 * 2 * 2 = 8

You could simply use that
pow(x,y) = exp(y*log(x))
which is also part of the implementation of the power function in the math library.

The recursion could help you:
public static int myPowerRec(int op1, int op2, int res) {
if (op2 == 0) {
return res;
}
else {
return (myPowerRec(op1, op2 - 1, op1 * res));
}
}
You will need to initialize res to 1 (myPowerRec(23, 2, 1) will give you 1 * 23 * 23).
This recursion is called tail recursion and will allow you to use this function without stack problem.
Be careful, you must check op2 value before.

Using a for loop:
public static int power(a, b) { // a ^ b
int p = 1;
for (int i = 1, i <= b; i++)
p *= a;
return p;
}

Related

How do I calculate powers in java using recursion based on this identity

The Identity being, xn = (xn/2)2 for all values where n is even and greater than 0.
How would I do this using a recursion method?
I'm finding myself stuck, and this is what I've been working with
public static double power(double base, int power){
if (power == 0){
return 1;
}
else if (power > 0 || power % 2 == 0){
???
}
public class Pow {
public static void main(String $[]){
System.out.println(pow(2,9));
}
public static double pow(double base, int power){
if (power == 0)
return 1;
//even
if((power&1)==0)
return pow(base*base,power/2);
//odd
return base*pow(base,power-1);
}
}
xn = (x2)n/2 if n is even
xn = x*xn-1 if n is odd
Point of using this approach is to compute the power in log(n) because it is dividing the power by two when its even.
You also need to account for the case where power is odd, and ideally also trap for the case when power is negative.
Just so that I'm not giving absolutely everything away, here's a JavaScript implementation:
function power(x, n) {
if (n < 0) {
return undefined; // uh-oh!
} else if (n === 0) {
return 1; // x^0 = 1
} else if (n % 2 === 0) {
const v = power(x, n / 2); // optimisation for even powers
return v * v;
} else {
return x * power(x, n - 1); // general case - x^n = x * x^(n-1)
}
}
You could also include an explicit test for x^1, but the code above works without it because the recursion terminates when it gets to calculating x * (x ^ 0).

How to recursively calculate a number raised to a power?

I have tried:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
This does not yield a value as I'm not sure how to do that.
public int calculatePower(int base, int powerRaised)
{
if (powerRaised != 0)
return (base*calculatePower(base, powerRaised-1));
else
return 1;
}
static int power(int x, int y)
{
// Initialize result
int temp;
if( y == 0) // Base condition
return 1;
temp = power(x, y/2); // recursive calling
if (y%2 == 0) //checking whether y is even or not
return temp*temp;
else
return x*temp*temp;
}
Well others have written solution which gives you correct answer but their time complexity is O(n) as you are decreasing the power only by 1. Below solution will take less time O(log n). The trick here is that
x^y = x^(y/2) * x^(y/2)
so we only need to calculate x^(y/2) and then square it. Now if y is even then there is not problem but when y is odd we have to multiply it with x. For example
3^5 = 3^(5/2) * 3^(5/2)
but (5/2) = 2 so above equation will become 3^2 * 3^2, so we have to multiply it with 3 again then it will become 3 * 3^(5/2) * 3^(5/2)
then 3^2 will be calculated as 3^(2/1) * (3^2/1) here it no need to multiply it with 3.
public static double pow(int a, int pow) {
if (pow == 0)
return 1;
if (pow == 1)
return a;
if (pow == -1)
return 1. / a;
if (pow > 1)
return a * pow(a, pow - 1);
return 1. / (a * pow(a, -1 * (pow + 1)));
}
Considering X as number and n as power and if both are positive integers
public static int power(int n, int X) {
if (n == 0) {
return 1;
} else if(n == 1) {
return X;
} else {
return X * power(n-1, X);
}
}
Let's re-write your function:
static public void power(int n, int X) {
System.out.print( + " ");
if (n>0) {
power(n-1, X);
}
}
First of all, lets change void to int.
Afterthat, when n equals to 1, we return the result as X, because X^1 = X:
static public int power(int n, int X) {
if (n>1) {
return X * power(n-1, X);
}
return X;
}
Scanner s = new Scanner(System.in) ;
System.out.println("Enter n");
int n = s.nextInt();
System.out.println("Enter x");
int x =s.nextInt();
if (n>0){
double pow =Math.pow(n,x);
System.out.println(pow);
}
While others have given you solutions in terms of code, I would like to focus on why your code didn't work.
Recursion is a programming technique in which a method (function) calls itself. All recursions possess two certain characteristics:
When it calls itself, it does so to solve a smaller problem. In your example, to raise X to the power N, the method recursively calls itself with the arguments X and N-1, i.e. solves a smaller problem on each further step.
There's eventually a version of the problem which is trivial, such that the recursion can solve it without calling itself and return. This is called base case.
If you are familiar with mathematical induction, recursion is its programming equivalent.
Number two above is what your code is lacking. Your method never returns any number. In the case of raising a number to a power, the base case would be to solve the problem for the number 0 as raising zero to any power yields one, so the code does not need to call itself again to solve this.
So, as others have already suggested, you need two corrections to your code:
Add a return type for the method.
State the base case explicitly.
public class HelloWorld{
public long powerfun(int n,int power,long value){
if(power<1){
return value;
}
else{
value = value * n;
return powerfun(n,power-1,value);
}
}
public static void main(String []args){
HelloWorld hello = new HelloWorld();
System.out.println(hello.powerfun(5,4,1));
}
}
I've tried to add comments to explain the logic to you.
//Creating a new class
public class RecursivePower {
// Create the function that will calculate the power
// n is the number to be raised to a power
// x is the number by which we are raising n
// i.e. n^x
public static int power(int n, int x){
// Anything raised to the 0th power is 1
// So, check for that
if (x != 0){
// Recursively call the power function
return (n * power(n, x-1));
// If that is true...
}else{
return 1;
} //end if else
} //end power
// Example driver function to show your program is working
public static void main(String[] args){
System.out.println("The number 5 raised to 6 is " + power(5,6));
System.out.println("The number 10 raised to 3 is " + power(10,3));
} //end psvm
} //end RecursivePower

Why doesn't my method call my other method with the right values?

I'm writing a program that lets the user enter a nominator and a denominator, which the program then converts to mixed form (9/8 -> 1 1/8 and so on). It works just fine, except for when the denominator is greater than the nominator. When I started debugging the code, I found something I couldn't understand. Below is the method fraction, which at the end of it calls the method gcd (greatest common divider) to determine what to divide the remainder of the integer division and the denominator with.
public static int[] fraction(int nominator, int denominator) //Rewrites a fraction to mixed form
{
//nominator == 7 and denominator == 8
int[] result = {0, 0, 0};
int quotient;
int remainder;
if (denominator == 0)
return null;
if (nominator == 0)
{
result[0] = 0;
result[1] = 0;
result[2] = 0;
return result;
}
kvot = nominator/denominator;
rest = nominator % denominator;
result[0] = quotient;
result[1] = remainder/(gcd(remainder, denominator)); //According to the debugger, the values are still 7 and 8 here
result[2] = denominator/(gcd(remainder, denominator));
return result;
}
When called with the above values, something seems to go wrong, because the values the second method recieves from the first is wrong. Instead of 7 and 8, it receives 7 and 1. Is the error in the code provided, or does it seem to be somewhere else?
public static int gcd(int a, int b) //Calculates the greatest common divider for two integers
{ //The debugger tells me that a == 7 and b == 1, even though the method was called with 7 and 8
int temp, c;
if (b == 0)
{
System.out.println("Nominator is 0, error");;
}
if (b > a)
{
temp = b;
b = a;
a = temp;
}
c = a % b;
a = b;
b = c;
return a;
}
Your gcd function is not ok. If you use the Euclid's algorithm you can calculate gcd like this
public static int gcd(int a, int b) //Calculates the greatest common divider for two integers
{
if (b == 0) {
return a;
} else {
return gcd(b, a%b);
}
}
You can also use some other solution, but the proposed is not ok.

Recursive Exponent Method

public static int exponent(int baseNum) {
int temp = baseNum *= baseNum;
return temp * exponent(baseNum);
}
Right now the method above does n * n into infinity if I debug it, so it still works but I need this recursive method to stop after 10 times because my instructor requires us to find the exponent given a power of 10.
The method must have only one parameter, here's some examples of calling exponent:
System.out.println ("The power of 10 in " + n + " is " +
exponent(n));
So output should be:
The power of 10 in 2 is 1024
OR
The power of 10 in 5 is 9765625
Do something like
public static int exp(int pow, int num) {
if (pow < 1)
return 1;
else
return num * exp(pow-1, num) ;
}
public static void main (String [] args) {
System.out.println (exp (10, 5));
}
and do not forget the base case (i.e a condition) which tells when to stop recursion and pop the values from the stack.
Create an auxiliary method to do the recursion. It should have two arguments: the base and the exponent. Call it with a value of 10 for the exponent and have it recurse with (exponent-1). The base case is exponent == 0, in which case it should return 1. (You can also use exponent == 1 as a base case, in which case it should return the base.)
The following is what my instructor, Professor Penn Wu, provided in his lecture note.
public class Exp
{
public static int exponent(int a, int n)
{
if (n==0) { return 1; } // base
else // recursion
{
a *= exponent(a, n-1);
return a;
}
}
public static void main(String[] args)
{
System.out.print(exponent(2, 10));
}
}
Shouldn't it have 2 parameter and handle exit condition like below?
public static int exponent(int baseNum, int power) {
if(power == 0){
return 1;
}else{
return baseNum * exponent(baseNum, power-1);
}
}
For recursion function, we need to :
check stopping condition (i.e. when exp is 0, return 1)
call itself with adjusted condition (i.e. base * base^(n-1) )
Here is the code.
public class Test
{
public static int exponent(int baseNum, int exp)
{
if (exp<=0)
return 1;
return baseNum * exponent(baseNum, --exp);
}
public static void main(String a[])
{
int base=2;
int exp =10;
System.out.println("The power of "+exp+" in "+base+" is "+exponent(base,exp));
}
}
Don't forget , for each recursive function , you need a base case. A stop condition`
static double r2(float base, int n)
{
if (n<=0) return 1;
return base*r2(base,n-1);
}
I came here accidentally, and I think one could do better, as one would figure out easily that if exp is even then x^2n = x^n * x^n = (x^2)^n, so rather than computing n^2-1 recursions, you can just compute xx and then call pow(x,n) having n recursions and a product. If instead the power is odd, then we just do xpow(x, n-1) and make the power even again. But, as soon as now n-1 is even, we can directly write xpow(xx, (n-1)/2) adding an extra product and using the same code as for the even exponent.
int pow_( int base, unsigned int exp ) {
if( exp == 0 )
return 1;
if( exp & 0x01 ) {
return base * pow_( base*base, (exp-1)/2 );
}
return pow_( base*base, exp/2 );
}

Calculating powers of integers

Is there any other way in Java to calculate a power of an integer?
I use Math.pow(a, b) now, but it returns a double, and that is usually a lot of work, and looks less clean when you just want to use ints (a power will then also always result in an int).
Is there something as simple as a**b like in Python?
When it's power of 2. Take in mind, that you can use simple and fast shift expression 1 << exponent
example:
22 = 1 << 2 = (int) Math.pow(2, 2)
210 = 1 << 10 = (int) Math.pow(2, 10)
For larger exponents (over 31) use long instead
232 = 1L << 32 = (long) Math.pow(2, 32)
btw. in Kotlin you have shl instead of << so
(java) 1L << 32 = 1L shl 32 (kotlin)
Integers are only 32 bits. This means that its max value is 2^31 -1. As you see, for very small numbers, you quickly have a result which can't be represented by an integer anymore. That's why Math.pow uses double.
If you want arbitrary integer precision, use BigInteger.pow. But it's of course less efficient.
Best the algorithm is based on the recursive power definition of a^b.
long pow (long a, int b)
{
if ( b == 0) return 1;
if ( b == 1) return a;
if (isEven( b )) return pow ( a * a, b/2); //even a=(a^2)^b/2
else return a * pow ( a * a, b/2); //odd a=a*(a^2)^b/2
}
Running time of the operation is O(logb).
Reference:More information
No, there is not something as short as a**b
Here is a simple loop, if you want to avoid doubles:
long result = 1;
for (int i = 1; i <= b; i++) {
result *= a;
}
If you want to use pow and convert the result in to integer, cast the result as follows:
int result = (int)Math.pow(a, b);
Google Guava has math utilities for integers.
IntMath
import java.util.*;
public class Power {
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int num = 0;
int pow = 0;
int power = 0;
System.out.print("Enter number: ");
num = sc.nextInt();
System.out.print("Enter power: ");
pow = sc.nextInt();
System.out.print(power(num,pow));
}
public static int power(int a, int b)
{
int power = 1;
for(int c = 0; c < b; c++)
power *= a;
return power;
}
}
Guava's math libraries offer two methods that are useful when calculating exact integer powers:
pow(int b, int k) calculates b to the kth the power, and wraps on overflow
checkedPow(int b, int k) is identical except that it throws ArithmeticException on overflow
Personally checkedPow() meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).
If you want get a long result, you can just use the corresponding LongMath methods and pass int arguments.
Well you can simply use Math.pow(a,b) as you have used earlier and just convert its value by using (int) before it. Below could be used as an example to it.
int x = (int) Math.pow(a,b);
where a and b could be double or int values as you want.
This will simply convert its output to an integer value as you required.
A simple (no checks for overflow or for validity of arguments) implementation for the repeated-squaring algorithm for computing the power:
/** Compute a**p, assume result fits in a 32-bit signed integer */
int pow(int a, int p)
{
int res = 1;
int i1 = 31 - Integer.numberOfLeadingZeros(p); // highest bit index
for (int i = i1; i >= 0; --i) {
res *= res;
if ((p & (1<<i)) > 0)
res *= a;
}
return res;
}
The time complexity is logarithmic to exponent p (i.e. linear to the number of bits required to represent p).
I managed to modify(boundaries, even check, negative nums check) Qx__ answer. Use at your own risk. 0^-1, 0^-2 etc.. returns 0.
private static int pow(int x, int n) {
if (n == 0)
return 1;
if (n == 1)
return x;
if (n < 0) { // always 1^xx = 1 && 2^-1 (=0.5 --> ~ 1 )
if (x == 1 || (x == 2 && n == -1))
return 1;
else
return 0;
}
if ((n & 1) == 0) { //is even
long num = pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
} else {
long num = x * pow(x * x, n / 2);
if (num > Integer.MAX_VALUE) //check bounds
return Integer.MAX_VALUE;
return (int) num;
}
}
base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).
public int power(int base, int n){
return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
}
There some issues with pow method:
We can replace (y & 1) == 0; with y % 2 == 0
bitwise operations always are faster.
Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.
public static long pow(long x, int y) {
long result = 1;
while (y > 0) {
if ((y & 1) == 0) {
x *= x;
y >>>= 1;
} else {
result *= x;
y--;
}
}
return result;
}
Use the below logic to calculate the n power of a.
Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n)
Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).
public int calculatePower1(int a, int b) {
if (b == 0) {
return 1;
}
int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
int temp = 1;
for (int i = 1; i <= val; i++) {
temp *= a;
}
if (b % 2 == 0) {
return temp * temp;
} else {
return a * temp * temp;
}
}
Apache has ArithmeticUtils.pow(int k, int e).
import java.util.Scanner;
class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++) {
try {
long x = sc.nextLong();
System.out.println(x + " can be fitted in:");
if (x >= -128 && x <= 127) {
System.out.println("* byte");
}
if (x >= -32768 && x <= 32767) {
//Complete the code
System.out.println("* short");
System.out.println("* int");
System.out.println("* long");
} else if (x >= -Math.pow(2, 31) && x <= Math.pow(2, 31) - 1) {
System.out.println("* int");
System.out.println("* long");
} else {
System.out.println("* long");
}
} catch (Exception e) {
System.out.println(sc.next() + " can't be fitted anywhere.");
}
}
}
}
int arguments are acceptable when there is a double paramter. So Math.pow(a,b) will work for int arguments. It returns double you just need to cast to int.
int i = (int) Math.pow(3,10);
Without using pow function and +ve and -ve pow values.
public class PowFunction {
public static void main(String[] args) {
int x = 5;
int y = -3;
System.out.println( x + " raised to the power of " + y + " is " + Math.pow(x,y));
float temp =1;
if(y>0){
for(;y>0;y--){
temp = temp*x;
}
} else {
for(;y<0;y++){
temp = temp*x;
}
temp = 1/temp;
}
System.out.println("power value without using pow method. :: "+temp);
}
}
Unlike Python (where powers can be calculated by a**b) , JAVA has no such shortcut way of accomplishing the result of the power of two numbers.
Java has function named pow in the Math class, which returns a Double value
double pow(double base, double exponent)
But you can also calculate powers of integer using the same function. In the following program I did the same and finally I am converting the result into an integer (typecasting). Follow the example:
import java.util.*;
import java.lang.*; // CONTAINS THE Math library
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n= sc.nextInt(); // Accept integer n
int m = sc.nextInt(); // Accept integer m
int ans = (int) Math.pow(n,m); // Calculates n ^ m
System.out.println(ans); // prints answers
}
}
Alternatively,
The java.math.BigInteger.pow(int exponent) returns a BigInteger whose value is (this^exponent). The exponent is an integer rather than a BigInteger. Example:
import java.math.*;
public class BigIntegerDemo {
public static void main(String[] args) {
BigInteger bi1, bi2; // create 2 BigInteger objects
int exponent = 2; // create and assign value to exponent
// assign value to bi1
bi1 = new BigInteger("6");
// perform pow operation on bi1 using exponent
bi2 = bi1.pow(exponent);
String str = "Result is " + bi1 + "^" +exponent+ " = " +bi2;
// print bi2 value
System.out.println( str );
}
}

Categories