Writing recursive method to compare even and odd digits within number - java

Basically, I am trying to write a method where a number is inputted and if there are more odd digits than even digits in the number, it returns "true", and else, false. I think I need to use tail recursion but I cannot figure it out.
public static boolean moreOddThanEven(int x) {
if (x == 0) {
return false;
}
if (x % 2 == 0) {
return moreOddThanEven(x / 10);
} else {
return moreOddThanEven(x / 10);
}
}
public static boolean moreOddThanEven2(int x) {
return moreOddThanEvenTR(x, 0, 0);
}
public static boolean moreOddThanEvenTR(int x, int odd, int even) {
if (x == 0) {
return false;
}
if (x%2==0) {
return moreOddThanEvenTR(x / 10, odd, even+1);
}
if (x%2!=0) {
return moreOddThanEvenTR(x / 10, odd+1, even);
}
if (odd <= even) {
return false;
} else {
return true;
}
}

I think using tail recursion is the right idea. Here is my attempt, assuming we can use more than one parameter in the recursive function:
public static boolean compareOddEven(int x, int count) {
//This is when we reach the end of the recursion (ones place).
if(x<10) {
//if odd, add 1, if even subtract 1
count += (x%2==1) ? 1 : -1;
return count>0;
}
else{
int digit = x;
//We use this loop in order to get the leftmost digit and read whether it is odd or even.
//Subsequently, we add or subtract 1 to the count based on the digit's parity and we pass this count into the next recursion in order to keep track.
while (digit > 9) {
digit /= 10;
}
count += (digit%2==1) ? 1 : -1;
//Get rid of the first digit to get next number to use in recursive call.
int removedFirstDigit = x % (int) Math.pow(10, (int) Math.log10(x));
//tail recursion
return compareOddEven(removedFirstDigit, count);
}
}
Explanation. We can accomplish this with just one method if we keep track of the count of odd and even digits the second parameter of the method. It will be less cumbersome to keep track of the count rather than keeping track of both counts of the odd and even numbers (and avoids the comparisons at the end which would not make it a tail recursion).
With this in mind, our approach is to start at the leftmost digit of the number we input and move to the right with each new recursive call. It is possible to start from right and go left in counting the parity of the digits as well.
So with every new recursive call, we pass in the count to the function as an argument. When we finally reach the ones digit, the nonnegativity of the count tells us whether there are more odd or even digits. To see this more clearly, I recommend printing out some of the arguments right before the recursive call is made.
Further note that when we reach the ones place, the truth value of count>0 will be propagated up the chain of recursive calls to give the final result that we desire.
Example call:
System.out.println(compareOddEven(21468233, 0));
Output:
false

There is a simple reason why you are stuck: you have to count the evens/odds like in 77778888888999. In fact you need to count the sum of (odds - evens), the oddity.
public static boolean moreOddThanEven(int x) {
assert x >= 0;
return x != 0 && oddity(x) > 0;
}
private static int oddity(int x) {
if (x == 0) {
return 0;
}
if (x % 2 == 0) {
return oddity(x / 10) - 1;
} else {
return oddity(x / 10) + 1;
}
}

Recursion is not needed (nor is more than one line):
public static boolean moreOddThanEven(int x) {
return (""+x).replaceAll("[02468]", "").length() > ((int) Math.log10(x)+1) / 2;
}
or the longer, but non-mathy version:
public static boolean moreOddThanEven(int x) {
return (""+x).replaceAll("[02468]", "").length() > ((int) (""+x).replaceAll("[13579]", "").length();
}

If you have an easier time thinking about loops than tail recursion, it's worth knowing that you can translate any loop into tail recursion (and vice versa, but that's different topic). First, we need to get the loop into this shape:
initialize a, b, ...
while (<some condition on a, b, ...>) {
Update a, b, ... using old values of a, b, ...
}
return <any function of a, b ...>
it translates to:
TypeOfReturn while_loop(TypeOfA a, TypeOfB b, ...) {
if (!(<some condition on a, b, ...>)) {
return <any function of a, b, c ...>;
}
Update a, b, ... using old values of a, b, ...
return while_loop(a, b, ...);
}
Let's apply this to your problem. As a loop:
// x is the input
int oddMinusEven = 0;
while (x) {
oddMinusEven += 2 * (x % 2) - 1;
x /= 10;
}
return oddMinusEven > 0;
We get:
bool hasMoreOddThanEvenDigits(int x, int oddMinusEven) {
if (!x) return oddMinusEven > 0;
oddMinusEven += 2 * (x % 2) - 1;
x /= 10;
return hasMoreOddThanEvenDigits(x, oddMinusEven);
}
We can clean this up a bit to make it less verbose:
int hasMoreOddThanEvenDigits(int x, int oddMinusEven) {
return x ? hasMoreOddThanEvenDigits(x / 10, oddMinusEven + 2 * (x % 2) - 1) : oddMinusEven > 0;
}
We run the loop with a "top level" function call that initializes variables:
return getMoreOddThanEvenDigits(x, 0) > 0;
It's fun to see what a good compiler does with the two codes. As you'd expect, they lead to nearly identical machine code. If we can do a rule-based transformation, so can the compiler.

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).

Issue with recursion because thread suspension

I was playing around with a few practice problems in Java. I wrote a recursive program for program given below. My solution is right except for the suspended (which I believe) gets back to active state and changes the value of the recursive method. I have also added a screenshot of Eclipse in debug mode where the thread stack is shown.
package com.nix.tryout.tests;
/**
* For given two numbers A and B such that 2 <= A <= B,
* Find most number of sqrt operations for a given number such that square root of result is a whole number and it is again square rooted until either the
* number is less than two or has decimals.
* example if A = 6000 and B = 7000, sqrt of 6061 = 81, sqrt of 81 = 9 and sqrt of 9 = 3. Hence, answer is 3
*
* #author nitinramachandran
*
*/
public class TestTwo {
public int solution(int A, int B) {
int count = 0;
for(int i = B; i > A ; --i) {
int tempCount = getSqrtCount(Double.valueOf(i), 0);
if(tempCount > count) {
count = tempCount;
}
}
return count;
}
// Recursively gets count of square roots where the number is whole
private int getSqrtCount(Double value, int count) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
++count;
getSqrtCount(sqrt, count);
}
return count;
}
public static void main(String[] args) {
TestTwo t2 = new TestTwo();
System.out.println(t2.solution(6550, 6570));
}
}
The above screenshot is from my debugger and I've circled the Thread stack. Can anyone try and run the program and let me know what the problem is and what would be the solution? I could come up with a non recursive solution.
Your recursion is wrong, since the value of count will return in any case 0 or 1 even if it goes deep down into recursive calls. Java is pass by value, meaning that modifying the value of a primitive inside of a method wont be visible outside of that method. In order to correct this, we can write the following recursion:
private int getSqrtCount(Double value) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
return getSqrtCount(sqrt) + 1;
}
return 0;
}
Your code is wrong, you should have
return getSqrtCount(sqrt, count);
instead of
getSqrtCount(sqrt, count);
Otherwise the recursion is pointless, you're completely ignoring the result of the recursion.

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

Recursive method to count figures in a number with boolean as return

I recently has a test in university and I was struggling with a problem. The task was defined very specifically as following:
Write a recursive method (don't change the signature, or parameters; no global variables allowed; don't use Strings or the method Stringbuffer; no loops) which returns "true" if the number of zeros in number "n" is odd and "false" if the number of zeros is even.
Signature and Parameter:
public static boolean oddZeros(int n) {
}
So for:
n = 10 //true
n = 100 //false
n = 1402050 //true
n = 0 // true
n = 12 // false
you get the idea..
I understand the concept of recursion but i fail to see how i can count something, given only booleans. I tried adding a counter variable inside the method but whenever i make a recursive call, obviously the variable would be reset to its initialization.
Since this is a very specific problem, i didn't find any solutions so far. How would a method like this look like?
public static boolean oddZeroes(int n) {
if (n < 10) {
return n == 0;
}
return (n % 10 == 0) ^ oddZeroes(n / 10);
}
You can even make it one-liner:
public static boolean oddZeroes(int n) {
return n < 10 ? n == 0 : (n % 10 == 0) ^ oddZeroes(n / 10);
}
And if you want to process negative inputs as well, add something like if (n < 0) {return oddZeroes(-n);} in the beginning, i.e.:
public static boolean oddZeroes(int n) {
if (n < 0) {
return oddZeroes(-n);
}
if (n < 10) {
return n == 0;
}
return (n % 10 == 0) ^ oddZeroes(n / 10);
}
You don't have to count anything.
You only have to observe that:
if you remove a 0 digit from a number that has an odd number of zeroes, the resulting (smaller) number does not have an odd number of zeroes.
if you remove a non 0 digit from a number that has an odd number of zeroes, the resulting (smaller) number also has an odd number of zeroes.
Finally, as the base of the recursion, if 0 < number < 10, it has an even number of 0s (0 0s), so your method should return false.
You can write a shorter implementation, but I preferred readability:
public static boolean oddZeros(int n) {
if (n == 0)
return true;
else if (n < 10)
return false;
else if (oddZeros (n / 10)) {
return n % 10 != 0; // removed digit is not 0
} else {
return n % 10 == 0; // removed digit is 0
}
}
EDIT:
This assumes the input is non-negative. If you need to support negative input, you can add an initial condition of:
if (n < 0) {
return oddZeros (-n);
}

Iteration, Recursion, and Multiplication

I am trying to understand what my instructor wants me to do. In his description " Design, implement and test a Java program Multiplication.java which includes an iterative method multIterative and a recursive method multRecursive. Both methods take the same parameters, the two positive integer numbers that will be multiplied and return the multiplication result. For both methods, use the technique of repetitive additions for achieving the multiplication of the two numbers. As an example, 4 multiplied by 6 should be calculated as 6 + 6 + 6 + 6 (i.e. four times six)."
I can understand the multiplication for recursion but not the iterative. Does he want me to make factorials? or what? I need help understanding. Examples would help!
A while loop should do the trick
public int multiIterative(int firstNum, int secondNum){
int result;
while(secondNum > 0){
result += firstNum;
secondNum--;
}
return result;
}
Thanks, but I came up with something like this too. can this work for an Iterative as well?
public static int multIterative(int a, int b) {
if (b == 0) {
return 1;
} else if (b < 0) {
return 0;
}
return a * multIterative(a, b - 1);
}
Alright then in recursion for my multRecursion() I did
public static int multRecursive(int a, int b) {
if (a == 0 || b == 0) {
return 0;
}
return multRecursive(a, b - 1) + a;
}

Categories