I have to make a recursive method which takes a double x, and int n, and return x^n. Initially I was going to just going to have something like this
public static double power(double x, int n){
if(n < 1){
return 1;
}else{
double total = x;
for(int i = 0; i < n-1; i++){
total = x*x;
power(total,x);
}
}
But in the problem it says "a recursive definition of this operation is x^n = x · x^n−1." I'm pretty new to Java and this way seems like it wouldn't be recursive as I would simply do x*x^n-1. I'm pretty new to Java so maybe I'm just confused but I'm just looking for some clarification on how that would be relate to a recursive method.
This is the easiest way that i can find:
public static double power(double x, int n){
if(n < 1){
return 1;
}else{
return x * power(x, n-1);
}
}
This is a solution:
public static double power(double x, double n){
if(n <= 1)
return x;
return x*power(x,n-1);
}
By using a for loop you are not solving the problem recursively.
Here is an example how you would use a for loop and a recursive method to do the same thing:
for(int i = 0;i<10;i++) //for loop
{
System.out.print(i);
}
public void print(int i) // recursive, call this method like so: print(0);
{
if(i<10)
{
System.out.println(i);
print(++i);
}
}
both techniques will print out the same result:
0
1
2
3
4
5
6
7
8
9
Related
given array of coins (int) and an int n the function need to return true if there is atleast one solution to the coin-change problem.
meaning: for array of ints> 0: [c(0) ,c(1) ,c(2) ,c(3) ,...... ,c(k)]. check if there is a solution for
the eqauation: a(0)*c(0)+ a(1)*c(1)+.....+ a(k)*c(k)= n. //n is the money we need to change
given c(0),c(1),....,c(n) >0 and a(0),a(1),....,a(n) =>0 both integers.
so I managed to make this code: the problem is that its algorithmic efficiency sucks, and this should be running on high values, and big coins array, so I need a code that is able to do this quicker.
public static boolean change(int[] coins, int n) {
boolean ans = false;
//loop running in recursion till founds ans/ passing limit
for (int i = 0; i < coins.length & (!ans); i = i + 1) {
if (n % coins[i] == 0) {
return true;
}
if (n >= coins[i]) {
ans = change(coins, n - coins[i]);
}
}
return ans;
}//O(n*k^n) solution for false ans , very bad :(
for example: for coins = {2,4,8} and n= 4111; I should get false, but the program unable to run this.
btw I would prefer this function to use recursion, but any solution/ guidnes is good :)
this is an other try doing this better but still not running as wanted.
//trying to use binary search and using divisions instead of minus
public static int iscashable(int[] coins, int n, int min, int max)
{
int check=(max+min)/2;
if(check == coins.length-1 | check == 0)
return check;
if(n/coins[check] > n% coins[check])
{
return (iscashable(coins,n,check,max));
}
else
{
return check;
}
}
public static int canchange(int[] coins, int n, int count)
{
int x=0;
int check= iscashable(coins,n,0,coins.length-count);
if(n%coins[check]==0)
{
return 0;
}
if(check==0)
{
return n;
}
if(n/coins[check] > n% coins[check])
{
x= (n/coins[check]) - (n% coins[check]);
int k= n-(coins[check]*x);
return canchange(coins, k, count+1);
}
else
{
return canchange(coins,n-coins[check],count+1);
}
}
the problem is both about runtime and number of recursion calls (with big number given, every recursion layer is coins.length^(num of layers));
I really thank you for your help!
I am attempting to use loops to find the exponent of a given base that produces a specific argument. For example, in the equation 5^x=625, 5 would be the base and 625 would be the argument. I know that in that equation x=4 but I am unsure of how to get 4 in my return.
Here is what I have so far:
public static int log(int base, int argument) {
int result = 1;
for (int i=0; i<=; i++)
result = ;
return result;
}
I am unsure what to put for my condition statement and my result. What am I missing here?
edit: I forgot to mention that I am attempting to do this without using the math library. I also thought it might help to include my code for finding the powers:
public static int pow(int base, int exponent) {
int result = 1;
for(int i=0; i<exponent; i++) {
result = result*base;
}
return result;
I essentially just trying to reverse this to find the exponent.
Something like that:
public static int log(int base, int argument) {
if(argument <= 0 || base <= 0) {
throw new IllegalArgumentException("This method only works with positive integers");
}
int result = 1;
int i = 0;
while(result < argument) {
result = result * base;
i++;
}
if(result == argument) {
return i;
} else {
throw new IllegalArgumentException("There is no integer for x in base^x = argument");
}
}
This as some flaws as it handle all cases but it's a start.
This is more of a math question.
For the formula 5^x = 625, you find x using x = log₅(625) = log(625)/log(5).
So:
public static int log(int base, int argument) {
return (int) (Math.log(argument) / Math.log(base));
}
But maybe you already knew this, since you named the method right.
Count how many times you can divide the argument by the base while the result is 1 or greater:
public static int log(int base, int argument) {
int result;
for (result=0; argument>=1 ; result++) {
argument = argument/base;
}
return result;
}
I'm trying to get an output that doubles the number I enter.
In my example, i put 5, and want my output to be 10, 8, 6, 4, 2. But I get an error saying
Exception in thread "main" java.lang.StackOverflowError
at HelloWorld.recursion(HelloWorld.java:13)
at HelloWorld.recursion(HelloWorld.java:13)
at HelloWorld.recursion(HelloWorld.java:13)
at HelloWorld.recursion(HelloWorld.java:13)
However, I've seen code similar to mine and they got it correctly, what am I doing wrong? Why is line 13 wrong?
public class HelloWorld{
public static void main(String []args){
System.out.println(recursion(5));
}
public static int recursion(int x){
int temp = x--;
if(x == 0){
return 0;
}
else if(x > 0){
return recursion(temp) + x*2;
}
return -1;
}
}
Let's walk through each line of this when recursion(5) is called.
public static int recursion(int x){ // x is 5
int temp = x--; // temp is 5, x is 4
if(x == 0){
return 0;
}
else if(x > 0){
return recursion(temp) + x*2; // calls recursion(5) again
}
return -1;
}
As others have mentioned above, you are using a post-decrement where you probably want a pre-decrement.
int x = 5, y = 5;
int a = x--; // a is 5, x is 4
int b = --y; // b is 4, y is 4
Change int temp = x--; to int temp = --x; Otherwise, your recursion is infinite.
public class HelloWorld{
public static void main(String []args){
System.out.println(recursion(5));
}
public static int recursion(int x){
int recursion(int x){
if(x == 0){
return 0;
}
else if(x> 0){
System.out.println(x*2);
recursion(--x);
}
}
You are using post-decrement to assign value to int temp:
int temp = x--; is the the same as int temp = x; x--;, so your argument for recursion in line 13 is the same as the previous function call. As a result of it, your recursion function gets into an infinite loop.
To get it to work, use pre-decrement instead, i.e.:
change int temp = x--; to int temp = --x;, which is equivalent to --x; int temp = x;. Now your argument in recursion(temp) is decremented by 1.
When you call a function, its data (like arguments and local variables) is put onto what is known as the function call stack. This stack has limited space, so if your recursion does not stop you get what is known as stack overflow. Now as for the code, others have pointed out what is wrong. temp is not being assigned the value that you think it is. I would recommend adding a print statement inside the recursive function to see what values of x are actually coming in. If for example, the same value is being passed in every time then the recursion is not really making any progress and will hit the stack size limit. Hopefully that will help you narrow down similar problems in the future. Happy debugging!
I had some code that calculates powers, by calling square, cube and hypercube methods. Currently the cube method calls the square method in the program, and then the hypercube method calls the cube method. I want to replace the calls to cube and hypercube with calls to the power method, but I'm completely stuck.
Here's the original code which worked.
public int square( int x ){
int i = ( x*x );
return i;
}
public int cube( int x ){
int i = (x * square(x) );
return i;
}
public int hypercube( int x ){
int i = (x * cube(x) );
return i;
}
public int power(int x, int n){
int k;
if (n==2){
k = square(x);
}
else if (n==3){
k = cube(x);
}
else if (n==4){
k = hypercube(x);
}
else if (n==1){
k = x;
}
else {
k = 1;
for (int i = 0; i < n; i++) {
k *= x;
}
}
return k;
}
Now like I said I want to replace the calls in the cube and hypercube methods with calls to the power method, then I still have calls to square, cube etc in the power method. So I want to remove calls to these methods entirely since I no longer need them. Its really bugging me.
This is what I have so far but its giving me StackOverFlowError.
public int square( int x, int n ){
int i = power( x, n );
return i;
}
public int cube( int x, int n ){
int i = power(x , n );
return i;
}
public int hypercube( int x, int n ){
int i = power(x , n );
return i;
}
public int power(int x, int n){
int k;
if (n==2){
k = square(x, n);
}
else if (n==3){
k = cube(x, n);
}
else if (n==4){
k = hypercube(x, n);
}
else if (n==1){
k = x;
}
else {
k = 1;
for (int j = 0; j < n; j++) {
k *= x;
}
}
return k;
}
First off, as you've recognized this is a very bad way of going about things. So anybody else reading this, apart from the usual call to avoid reinventing the wheel (unless it's for educational purposes) don't implement your exponentiation methods this way!
That being said, the reason you're getting a stack overflow (so appropriate) is that you have a circular definition. The simplest way to see this is trying to track down how power works by hand. Let's say I want to run power(3, 2). What happens? Well power(3, 2) recognizes this as an instance of n == 2 and so goes to the square method. However, the square method relies on the power method to get things done and then you repeat ad infinitum. Hence you get function calls piling up on your stack until you run out of space.
P.S. Incidentally, if you are looking at implementing integer exponentiation for personal edification, you might want to look into repeated squaring. It makes your code much faster (a logarithmic number of multiplication operations as opposed to a linear number).
It looks to me that there is an infinite cycle going on here.
If n=2, then power calls sqaure which in turn calls power and n doesn't change either.
You get StackOverFlowError usually when you deal with infinities.
power(x,n) must be independent of cube or square if you want to get rid of those.
I want a program that takes an int x as parameter and returns 2^x. The implementation is not allowed to use power of.
public int double2 (int x) {
int r = 2;
int y = 1;
for (int i=0; i < x; i++){
y = r* y;
}
return y;
}
Do you think this is a right solution?
The solution you posted using the for loop produces the right result, but you should look into a more efficient solution (bit shifting) as Adamski first mentioned.
How about this:
int power = someNumberHere;
int result = 1;
while (power-- > 0) result *= 2;
And I think that is what you want...I think. Are you trying to find a power of two? Maybe expand the question, scope and reasons behind what you want a little.
y = x*x;
or
y = x*2;
or
y = 42; // ;)
Depending in what do you mean by the "double of 2".
EDIT
naive implementation
public int 2powerOf( int n ) {
int r = 2;
for( int i = 1 ; i < n ; i++ ) {
r = r * 2;
}
return r;
}
It is almost as the one you posted, this might not handle negative values though.
If you want to know if yours works, then run it and find out for your self.
Just in case if you need such kind of explanatory code (it's in C though).
#include <stdio.h>
int main(void)
{
int base, power, index;
long answer;
base = 0;
power = 0;
answer = 1.00;
printf(" Enter a base number: ");
scanf("%d", &base);
printf(" Enter a power to raise the base to: ");
scanf("%d", &power);
for(index = 1; index <= power; index++)
answer = answer * base;
printf("%d raised to the power of %d is %ld.", base, power, answer);
getchar();
getchar();
return 0;
}
Does your implementation passes the following JUnit test?
import junit.framework.TestCase;
public class YourClassTest extends TestCase {
private YourClass sut = new YourClass();
public void testPowersOfTwo() {
assertEquals(1, sut.double2(0));
assertEquals(2, sut.double2(1));
assertEquals(4, sut.double2(2));
assertEquals(8, sut.double2(3));
assertEquals(16, sut.double2(4));
}
}
If it does, it is a working solution (but maybe not optimal).