From Python to Java: Proper while loop declaration - java

How do I write this code in Java?
def gcd(a, b):
"""
Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
It seems I can't do while (b) { in Java because of Type mismatch error. It seems I also can't do the line a, b = b, a%b exactly in Java as well.

public static int gcd(int a, int b) {
int temp;
while(b != 0) {
temp = a;
a = b;
b = temp % b;
}
return a;
}
Java expects the condition of the while to be a boolean, not an int.
The a, b = b, a%b syntax will not work in Java. You need to do the assignments individually.
So you can set a = b, and then set b = a % b. I used a temp variable to hold the old value of a so that I can compute a % b (before I overwrote a with a = b).

Do you really need a while? It can be as simple as-
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}

Related

Return the larger value if it is in the range 10..20

I am trying to work out this problem on codingbat and the problem is Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range. The solution has been given below but I can not understand the first part as the comment says larger value is a, but the code says( b > a ) and what does this mean: int temp = a; a = b; b = temp;. Can anyone please explain it...
public int max1020(int a, int b) {
// First make it so the bigger value is in a
if (b > a) {
int temp = a;
a = b;
b = temp;
}
// Knowing a is bigger, just check a first
if (a >= 10 && a <= 20) return a;
if (b >= 10 && b <= 20) return b;
return 0;
}
The first if statement makes sure that a is not smaller than b (if a is smaller than b, it swaps a and b - that's what the 3 assignment statements involving the temp variable do).
The second if statement returns a if it's in the required range (and at this point we know a >= b).
If not, the third if statement returns b if it's in the required range.
Otherwise 0 is returned (when both a and b are not in the required range).
It says that if the value of b is greater than that of a, switch the 2 values. So, for example, if a = 10 and b = 15:
if (b > a) { is true so will get in the if
int temp = a; temp will take the value 10
a = b; a will take the value 15
b = temp; b will take the value 10
So, the values of a and b will be switched, if the value of b is greater than that of a. Therefore, a will have the bigger value.

How to get the goldenRatio using recursion in Java?

I'm working on this simple java recursion problem given the following directions:
Calculate the golden ratio.
Given two numbers a and b with a > b > 0, the ratio is b / a.
I have done some code but I'm stuck on getting the recursion working properly. Here's my code:
public class MyTesting {
public static void main(String[] args) {
System.out.println(ratio(8 , 4));
}
public static double ratio(int a, int b) {
int goldelRatio = 0;
if(a > b && b > 0){
return goldelRatio = a / b;
}
return goldelRatio;
}
}
How about something like this:
double goldenRatio(double a, double b, double epsilon) {
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b, epsilon);
}
}
This way you achieve what you need in one function, with epsilon deciding how fine the resolution would be.
Also as an added bonus, and although Java doesn't have (at the time of writing this at least) tail recursion optimization, in theory this function could be optimized by tail recursion.
example with hard coded epsilon:
double goldenRatio(double a, double b) {
double epsilon = 0.00001;
if(Math.abs((b / a) - ((a + b) / b)) < epsilon) {
return ((a + b) / b);
} else {
return goldenRatio(b, a + b);
}
}
example run:
public static void main(String[] args) {
double goldenRation1 = goldenRatio(1.0, 1.0);
System.out.println(goldenRation1); // prints 1.618032786885246
System.out.println(goldenRation1 > 1.61800 && goldenRation1 < 1.61806); // prints true
double goldenRation2 = goldenRatio(100.0, 6.0);
System.out.println(goldenRation2); // prints 1.6180367504835589
System.out.println(goldenRation2 > 1.61800 && goldenRation2 < 1.61806); // prints true
}
Yours is not a recursive function, a recursive function that calculates Golden Ratio would look like the one below.
private int MAX_COUNTER = 50;
private int count = 0;
public double ratio(double a, double b) {
count++;
double goldenRatio = b / a;
if (count < MAX_COUNTER) {
return ratio(b, a + b);
}
return goldenRatio;
}
NOTE: I put the counters because given that is a recursive function trying to find a number with infinite decimals, it will cause the JVM to go on StackOverflow :) , so we got to stop it sooner or later.
Recursion mainly means methods calling themself, meaning you should try something like that:
public double recursionMethod(int a, int b){
int c = a+b;
if(Math.abs(ratio(b,a)-ratio(c,b))< (double) 1/42)
return ratio(c,b);
else
return recursionMethod(b,c);
}
1/42 is just your accuracy, you can implement any other breaking condition you like. Call this method in main with arguments (1,1).

it isn't reading my number inputs in the original class

My code isn't seeing the input numbers from the second class. It keeps thinking all the inputs are zero so it isn't completing the program. Where did I go wrong?
I've tried a couple different things that I could think of, but it didn't work. It keeps outputting false/unsolvable because all the numbers are zero instead of the inputs.
The second class is just the number inputs.
private static int a, b, c, d, e, f;
public static void main(String args[]) {
System.out.println("Please enter numbers for 'a, b, c, d, e, f' ");
Chapter9_2ndclass c2 = new Chapter9_2ndclass(a, b, c, d, e, f);
Exercise_09_11 Chapter9_2ndclass = new Exercise_09_11(a, b, c, d, e, f);
// Exercise_09_11 getY = new Exercise_09_11(a, b, c, d, e, f);
// //constructors
if (Chapter9_2ndclass.isSolvable()) {
Chapter9_2ndclass.getX();
Chapter9_2ndclass.getY();
} else {
System.out.println("Unsolvable");
}
}
public Exercise_09_11(int a, int b, int c, int d, int e, int f) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
public boolean isSolvable() {
double isSolvable = ((a * d) - (b * c));
System.out.println(isSolvable);
if (isSolvable != 0) {
System.out.println("True");
return true;
} else {
System.out.println("False");
System.out.println("The 'isSolvable' number is, " + isSolvable);
return false;
}
}
public int getY() {
int Y = ((a * f) - (e * c)) / ((a * d) - (b * c));
return Y;
}
public int getX() {
int X = ((e * d) - (b * f)) / ((a * d) - (b * c));
return X;
}
You are creating a new instance of Chapter9_2ndclass and Exercise_09_11, and assigning it your private static ints through their constructors.
Primitive int defaults to 0 when unassigned in this context, hence you get all 0s.
You probably want to assign them by parsing arguments of the command-line execution as int in your main method.
All variables are zero because they are not initialized and you passed the variable to the contructor of Chapter9_2ndclass and Exercise_09_11 which causes default value of int ie 0 to be passed and initializing them to 0
The problem is that you are never reading any input from the user and setting the values. Specifically, the static int declarations a, b, c, d, e, and f default to 0 and are never set.

the left-hand side of the assignment must be a variable

private static int setGCD()
{
int a, b;
gCD(a,0) = a; //here -the left-hand side of the assignment must be a variable//
gCD(a,b) = gCD(b,a%b); //here -the left-hand side of the assignment must be a variable//
finalNumer = enterNumer/gCD; //here -cannot make static reference to finalNumer, enterNumer, or gCD//
finalDenom = enterDenom/gCD;//here -cannot make static reference to finalDenom, enterDenom, gCD
}
This method’s purpose is to find the Greatest Common Denominator (GCD) of a numerator and denominator entered by the user in the above programming. But I keep getting the stated errors (in the comments), which is confusing me because that was the way my teacher wrote it on the board, but it made absolutely no sense to me! Please help!
There are 2 implementations for the Euclidean algorithm:
Iterative (pseudocode):
function gcd(a, b)
while a ≠ b
if a > b
a := a − b
else
b := b − a
return a
Recursive (pseudocode):
function gcd(a, b)
if b = 0
return a
else
return gcd(b, a mod b)
I believe that you want the latter, based on what you have written:
public static int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
Pretty easy to turn pseudocode into proper Java.
This function returns what you are looking for, then you can use its output to set gcd wherever you like:
public static int gcd(int a, int b)
{
while (a != b)
{
if (a > b)
{
a = a - b;
}
else
{
b = b - a;
}
}
return a;
}
See the wiki article on Euclidean Algorithm.

If equivalent without using conditional operations and other loop methods java

int function(int a, int b, int c){
if(a==c)
return a;
else
return b;
}
Question is to achieve a same o/p without using if, while, do, for, switch,conditional expression(?:) and other general inbuilt methods like equals
Please tell me the logic and code..
Here's one fairly straightforward option:
int function(int a, int b, int c) {
java.util.HashMap<Boolean, Integer> map = new java.util.HashMap<Boolean, Integer>();
map.put(true, a);
map.put(false, b);
return map.get(a == c);
}
Using maps to emulate switch statements in languages that don't have them is pretty common. Using them to emulate if statements is probably an abuse.
Here's an approach using operators only:
int function(int a, int b, int c) {
//If a == c: result = 0x00000000
//Else: result = 0xFFFFFFFF
int result = (a - c | c - a) >> 31;
//If a == c: result = 0x00000000 & (a ^ b) = 0
//Else: result = 0xFFFFFFFF & (a ^ b) = a ^ b
result &= a ^ b;
//If a == c: result = 0 ^ a = a
//Else: result = (a ^ b) ^ a = b
result ^= a;
return result;
}
I really wish I came up with Cairnarvon's solution. Here's what I got, but in any case you'll end up using conditional statements somewhere hidden in a function call, unless you can figure out how to do this with bitwise operators.
public static int fn(int a, int b, int c) {
Boolean equal = (a == c);
//if equal is false, compareTo will return 0.
//if equal is true, compareTo will return any positive integer, thus we take mod 2 to ensure this is 1
int ret_a = equal.compareTo(Boolean.FALSE) % 2;
//if ret_a is 0, make ret_b = 1
//if ret_a is 1, make ret_b = 0
int ret_b = (ret_a + 1) % 2;
//one of these two terms is guaranteed to be zero, therefore you will only
//return the value of a, or b.
return (ret_a * a) + (ret_b * b);
}
Here is my attempt at a solution with no comparison or bit twiddling. Sadly as #Pshemo pointed out my logic is flawed.
public static int fn(int a, int b, int c) {
//I assumed this will return 1 if not a != c
//See Pshemo's comment about why this is wrong.
int not_equal = ((a - c) * (a - c) ) % 2;
int ret_a = (not_equal + 1) % 2;
int ret_b = not_equal;
//one of these two terms is guaranteed to be zero, therefore you will only
//return the value of a, or b.
return (ret_a * a) + (ret_b * b);
}
There are a number of possible approaches, including:
Do the test in native code. That's cheating.
Find some library class that can used to do the job. There are probably lots of variations on this approach; e.g. see #Cairnarvon's answer.
Do something tricky to generate an exception (or not) depending on the inputs. My initial idea was to use division by zero, but here's another way ...
int insanelyStupidConditional (int a, int b, int c) {
int[] dummy = new int[1];
try {
int foo = dummy[a - c];
} catch (ArrayIndexOutOfBoundsException ex) {
return b;
}
return a;
}
Bit twiddling ... like #Vlad's answer
Anyway, the point of the interview question is not the answer, but whether you are able to think outside of the box to arrive at something. The most practical answer is "change the requirements ... this is insane".
Another way
Base idea return b * f(a,c) + a * (1 - f(a,c)) where
f(a,c) -> 1 for a != c
f(a,c) -> 0 for a == c
so
for a!=c we will return b*(1) + a*(0);
and for a==c we will return b*(0) + a*(1);
code
public static int test(int a, int b, int c) {
// (a - c) | (c - a) will give
// for a != b negative value
// for a == c zero
// to get sign of that value we need to get highest bit
// so >>>31 will do the trick
int signum = ((a - c) | (c - a)) >>> 31;
//for a == c -> signum = 0
//for a != c -> signum = 1 (it indicates that (a - c) | (c - a) was negative)
return b * signum + a * (1 - signum);
}
There you go, no if, while, do, for, switch, inline if (?:), or any other operator (==, !=, >, <, >=, etc.):
int function(int a, int b, int c){
int[] result = {-1, a, b};
return result[new TreeSet<Integer>(Arrays.asList(a, c)).size()];
}
Logic: Adds both a and c to a Set. If they are equal, they'll be added only once, and the set's size will be 1. If they are different, the size will be 2.

Categories

Resources