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

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.

Related

Finding Greatest Common Divisor using Euclidean Algorithm

I was trying to figure out a solution by which I can find GCD of 2 numbers in most optimal way,
So I need some help here to figure out whether the program I came out works for all possible cases or has any case it will break down or can I improve it more to make it an optimal solution.
Program:
public static void main(String[] args) {
int a= 153;
int b= 81;
boolean flag = true;
int gcd = 1;
while(flag)
{
if(a>b && a%b ==0)
{
flag = false;
gcd = b;
}
else if(b>a && b%a ==0)
{
flag=false;
gcd = a;
}
else if( a>b)
a = a-b;
else
b = b-a;
}
System.out.println(gcd);
}
Kindly help me out in figuring out the proper solution , thanks in advance.
Try something like this. Euclids GCD algorithm basically says this: GCD of 2 numbers (we will call them bigger and smaller) is equal to the GCD of smaller number and difference between bigger and smaller number. Repeat the procedure until two numbers are the same.
The below is iterative solution.
int a= 153 , b = 81, gcd = 1;
while( gcd != a ) {
if( a > b ) a -= b;
else if( b > a) b -= a;
else gcd = a;
}
System.out.println(gcd);
This is recursive solution. Hope this helps.
public static int euclidGCD(int a, int b) {
if (b == a) return a;
if (b > a) return euclidGCD(b - a, a);
else return euclidGCD(a - b, b);
}
Here is a modification of your program.
To test a program the best thing is to write down its conditions and cases.
In this exercise there are two conditions:
1.) Number must be integer
2.) Number must be positive.
Dealing with numbers usually has discrete number of cases. In this exercise there are two cases:
1.) Numbers are equal.
2.) Numbers are different.
Your code is not correct when a is equal to b (try it yourself). When the numbers are different your code works fine. Below is modification.
int a= 55;
int b= 55;
boolean flag = true;
int gcd = b;
while(flag && b != a)
{
if(a>b && a%b ==0)
{
flag = false;
gcd = b;
}
else if(b>a && b%a ==0)
{
flag=false;
gcd = a;
}
else if( a>b)
a = a-b;
else
b = b-a;
}
System.out.println(gcd);

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

From Python to Java: Proper while loop declaration

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

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.

How to create Fibonacci Sequence in Java

I really suck at math. I mean, I REALLY suck at math.
I'm trying to make a simple fibonacci sequence class for an algorithm I'll be using. I have seen the python example which looks something like this:
a = 0
b = 1
while b < 10:
print b
a, b = b, b+a
The problem is that I can't really make this work in any other language. I'd like to make it work in Java, since I can pretty much translate it into the other languages I use from there. This is the general thought:
public class FibonacciAlgorithm {
private Integer a = 0;
private Integer b = 1;
public FibonacciAlgorithm() {
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
public Integer getValue() {
return b;
}
}
All that I end up with is doubling, which I could do with multiplication :(
Can anyone help me out? Math pwns me.
I'd do it this way:
public class FibonacciAlgorithm {
private int a = 0;
private int b = 1;
public FibonacciAlgorithm() {
}
public int increment() {
int temp = b;
b = a + b;
a = temp;
return value;
}
public int getValue() {
return b;
}
}
This keeps it as close to your original Java code as possible.
[Editor's note: Integers have been replaced with ints. There is no reason to use Integers for this.]
The line
a, b = b, b+a
Doesn't easily translate. It's something like this. You could simplify it. This is the literal meaning.
t1 = b
t2 = b+a
a = t1
b = t2
You need to store the value of either a or b in a temporary variable first;
public Integer increment()
{
int temp = a;
a = b;
b = temp + b;
return value;
}
Java integers can only store the first 46 Fibonacci numbers, use a lookup table.
I'll just translate your earlier code:
public void fibb(int max) {
int a = 0;
int b = 1;
while (a < max) {
System.out.println(a);
int temp = a + b;
a = b;
b = temp;
}
}
Don't you want to create a function to return the nth Fibnoacci number? This is how I remember it being taught when I was a kid:
public int Fibb(int index) {
if (index < 2)
return 1;
else
return Fibb(index-1)+Fibb(index-2);
};
Given the definition being the first pair of Fibbonaci numbers are 1 and everything else is based off of that. Now, if you merely want to print out the Fibonaccis a loop may be simpler which is what a lot of the other replies cover.
The main problem with your Python-to-Java translation is that Python's assignment statement up there is executed all at once, while Java's are executed serially. Python's statement is equivalent to saying this:
Make a list out of 'b' and 'a + b'
Make another list out of references to 'a' and 'b'
Assign all the elements from the second list to the first one
(It might actually be a tuple, I'm not exactly fluent in Python.)
So the 'b' and 'a+b' resolve to values before they are assigned. You can't do that kind of multiple-simultaneous assignment in Java.
In general, a statement in Python like
var1, var2, ...varN = expression1, expression2, ...expressionN
is going to translate in Java to
temp1 = expression1;
temp2 = expression2;
...
tempN = expressionN;
var1 = temp1;
var2 = temp2;
...
varN = tempN;
This way all the expressions resolve to values before the assignments happen, and none of the assignments have side effects on the expressions.
If I were doing this for real I'd probably do the lookup table and store longs (since Fibonacci numbers grow vaguely exponentially and I'd want to go past 46). The iterative form, like you have, will take O(N) to calculate the Nth Fibonacci value; the typical recursive formulation will take as many function calls as the returned value. Fibonacci practically begs for the answers to be cached somewhere, and this would make the recursive form much more feasible.
There was a recursive solution posted above, but this solution is tail recursive so it grows linearly.
public class Fibonacci {
public long fibonacci(int number) {
return fib(0,1,number);
}
private long fib(long result, long next, int n) {
if (n == 0)
return result;
else
return fib(next, result+next, n-1);
}
}
i'll do this
fib = 100;
for(int a = 1, b = 0;a <= fib;a += b, b = (a-b)) {
System.out.print(a + ",");
}
public Integer increment() {
a = b;
b = a + b;
return value;
}
Is certainly wrong. I think switching the first two lines should do the trick

Categories

Resources