How to recursively calculate a number raised to a power? - java

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

Related

Java recursion 1234 to 4321 for example

I have a question how to better tackle this task, I have a version, but I am sure there is a better and shorter way to do this maybe. I need to take any int number(return it as an int without turning it into a String), but never with a 0 at the end (100, 120) but like 1234, or 4132. I need to take this number and using recursion rewrite it the other way around example 1234 to 4321, 4132 to 2314, maybe there is a way this is called, i personally don't know about it.
Here is what I got:
public static int reverse(int r, int n, int k){
if(r==0)
return 0;
else
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1)
}
public static void main(String[] args) {
System.out.println(reverse(1234, 4, 0));
}
Working with a String representation of the int may make the code more readable.
Try:
Integer.parseInt(new StringBuilder(r+"").reverse().toString());
Current code doesn't compile. Added a ) to this line:
from if(r==0{ change to if(r==0){
and added a ; in this line return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
Your code after this two changes will look like:
public static int reverse(int r, int n, int k){
if(r==0)
{
return 0;
}else{
return + (r%10) * (int)Math.pow(10, (n-k-1))+reverse (r/10, n, k+1);
}
}
if the number ends with 0, the program will not show any special message to the user, i.e 1230 will return 321. In this case, maybe
maybe print a message ("number must not end with a 0) or throw an exception?
Didn't notice the recursion part.
public static void main(String[] args) {
int i = 589;
System.out.println(reverse(i));
}
public static int reverse(int k){
if(k/10 == 0){return k;}
else return (k%10 * (int)Math.pow(10, (int)Math.log10(k))) + reverse(k /10);
}
Explanation:
k%10 gives you the last digit of an int
(int) (Math.log10(k)) returns
number of Digits in an Integer minus one
public static final int reverse(int number) {
final int lastDigit = number % 10;
final int length = (int) Math.log10(number);
return (number < 10) ? number : (int) (Math.pow(10.0, length) * lastDigit + reverse(number / 10));
}
If the number is lower then 10 it's the number itself. Otherwise it's the last digit multiplied with 10^n where n is the length of the number, so it's now at the position for the first digit.
Then add the result of a reverse of the rest number to it (the number without the last digit).
You take advance of the recursion function itself as it would already work to solve the big problem. You only have to think about the trivial end condition and one single step (which mostly is something you would suggest as the last step)
This is the best way that I could make it using recursion and without conversions.
private static int myReverse(int n, int r) {
if(n == 0)
return r;
int newR = r*10 + n%10;
return myReverse(n/10, newR);
}
What I'm doing here is:
Two parameters: n - the number you want to reverse, r - the reversed number
The recursion stops when n equals 0 because it always dividing it by 10
newR - This variable is unnecessary but it´s better for 'understanding' porposes, first I multiply r by 10 so I can sum the last value o n. For example, reverse 123: along the way if r = 12 and n = 3, first 12*10 = 120, n%10 = 3 then r*10 + n%10 = 123
A 'pleasant' way with only one return statement:
private static int myReverse2(int n, int r) {
return n == 0 ? r : myReverse2(n/10, r*10 + n%10);
}

Find a number to the power of another number?

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

How to find out if two numbers are relatively prime?

I'm trying to write a method that will calculate if two numbers are relatively prime for an assignment. I'm primarily looking for answers on where to start. I know there is a method gcd() that will do a lot of it for me, but the assignment is pretty much making me do it without gcd or arrays.
I kind of have it started, because I know that I will have to use the % operator in a for loop.
public static boolean relativeNumber(int input4, int input5){
for(int i = 1; i <= input4; i++)
Obviously this method is only going to return true or false because the main function is only going to print a specific line depending on if the two numbers are relatively prime or not.
I'm thinking I will probably have to write two for loops, both for input4, and input5, and possibly some kind of if statement with a logical && operand, but I'm not sure.
Well in case they are relatively prime, the greatest common divider is one, because - if otherwise - both numbers could be devided by that number. So we only need an algorithm to calculate the greatest common divider, for instance Euclid's method:
private static int gcd(int a, int b) {
int t;
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a;
}
And then:
private static boolean relativelyPrime(int a, int b) {
return gcd(a,b) == 1;
}
Euclid's algorithm works in O(log n) which thus is way faster than enumerating over all potential divisors which can be optimized to O(sqrt n).
Swift 4 code for #williem-van-onsem answer;
func gcd(a: Int, b: Int) -> Int {
var b = b
var a = a
var t: Int!
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a
}
func relativelyPrime(a : Int, b: Int) -> Bool{
return gcd(a: a, b: b) == 1
}
Usage;
print(relativelyPrime(a: 2, b: 4)) // false
package stack;
import java.util.Scanner; //To read data from console
/**
*
* #author base
*/
public class Stack {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // with Scanner we can read data
int a = in.nextInt(); //first variable
int b = in.nextInt(); //second variable
int max; // to store maximum value from a or b
//Let's find maximum value
if (a >= b) {
max = a;
} else {
max = b;
}
int count = 0; // We count divisible number
for (int i=2; i<=max; i++) { // we start from 2, because we can't divide on 0, and every number divisible on 1
if (a % i == 0 && b % i==0) {
count++; //count them
}
}
if (count == 0) { // if there is no divisible numbers
System.out.println("Prime"); // that's our solutions
} else {
System.out.println("Not Prime"); //otherwise
}
}
}
I think that, this is the simple solution. Ask questions in comments.

Determining if a number is a factorial

I have to write a method that indicates if a number is a factorial of a number. Basically whatever number the user inputs, the method should be able to tell if that number (x) is a factorial of another number. I've written a method that finds the factorial of (x), but I need to know if (x) is a factorial of another number. I've been using 6 as an example for now since 6 is the factorial of 3. Any suggestions?
public static int Fact(int x) {
int y=1;
while(x>1) {
y=y*x;
x=x-1;
}
return y;
}
A factorial is of the form (1) * 2 * 3 * 4..., So I'd just start multiplying those numbers until you either reach or overshoot your number.
It should be quite simple.
As fact n = 1*2*3*4*..n , (n%i)==0 should always be true for i in [1,n]
This should work fine
public class Factorial {
public static boolean isFactorial(int x){
int i =x;
boolean bol = false;
for ( i=2 ; i<x ; i++ ) {
if ((x%i)==0) bol = true ;
else bol = false ;break;
}
return bol;
}
}
And you can test it with this class :
public class TestFact {
public static void main(String[] args) {
System.out.println(Factorial.isFactorial(120));
}
}
Take a look at the mod operator. If the number mod some other number = 0 then you have found a factor. (Assuming this is what you are looking for). For example:
public static int Fact(int x){
int i=2;
while(x % i (has no remainder) || (stop criteria))
i++;//increment the number
if(x!=i)//you found a factor
return i;
return -1;
}

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

Categories