Finding Greatest Common Divisor using Euclidean Algorithm - java

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

Related

Finding and Printing the First Digit in Ones Place

Write a method this passed two integers which returns true if the two numbers x and y have the same number in the ones place.
My Code:
int number;
while( number > 0) {
print (number%10);
number = number/10;
I know this is wrong but I am not sure where to start; I am a beginning coder.
What you can do is convert the integers to a String and get the character at the last index and see if they are equal.
public void lastDigitEqual(int a, int b){
String astring = Integer.toString(a);
String bstring = Integer.toString(b);
if(astring.charAt(astring.length()-1) == bstring.charAt(bstring.length()-1)){
System.out.println("True");
}else{
System.out.println("False");
}
}
Or another way of doing it is just getting the numbers mod 10. This will return the remainder of the two numbers when they are divided by 10, which will basically just be the ones digit. Then, you can check if they are equal.
public void lastDigitEqual(int a, int b){
int amod = a % 10;
int bmod = b % 10;
if(bmod == amod){
System.out.println("True");
}else{
System.out.println("False");
}
}
I tested both these ways and they work.

GCD of two polynomials

In the code below I want to find Greatest Common Divisor of 2 polynomials.
Sometimes I am getting error on " return c.plus( (a.minus(b.times(c)).divides(b)) );". How can I fix it?
public Polynomial divides(Polynomial b) {
Polynomial a = this;
if ((b.deg == 0) && (b.coef[0] == 0))
throw new RuntimeException("Divide by zero polynomial");
if (a.deg < b.deg) return new Polynomial(0,0);
int coefficient = a.coef[a.deg]/(b.coef[b.deg]);
int exponent = a.deg - b.deg;
Polynomial c = new Polynomial(coefficient, exponent);
return c.plus( (a.minus(b.times(c)).divides(b)) );
}
public Polynomial GCD(Polynomial b) {
Polynomial a = this;
Polynomial f = b;
Polynomial x = a.minus((a.divides(f)).times(f));
if (x.deg == 0 && x.coef[0] == 0) {
return b;
}
return f.GCD(x);
}
That runtime exception means: you created an endless recursion.
Most likely, because your method divides() is calling itself on that last row - without proper checking in there to avoid that recursion.
In other words: you want to review your maths and the logic in there to simply avoid that divides() keeps calling itself without any limits!

Comparison for BigInteger not working

I'm not getting the output that I'm expecting. This is for a primality test. I'm not really sure what's wrong. Either my loop isn't working correctly, or this isn't.
n is a BigInteger. It's a random generated by user inputted length.
public static boolean isPrime(BigInteger n) {
BigInteger zero = new BigInteger("0");
BigInteger one = new BigInteger("1");
BigInteger two = new BigInteger("2");
BigInteger three = new BigInteger("3");
System.out.println(n + " Mod 2 " + n.mod(two));
if (n.compareTo(one) == 0 || n.compareTo(one) < 0) {
//System.out.println("HIT1");
return false;
} else if (n.compareTo(three) == 0 || n.compareTo(three) < 0) {
//System.out.println("HIT2");
return false;
} else if ((n.mod(two)).compareTo(zero) == 0 || (n.mod(three)).compareTo(zero) == 0) {
//System.out.println("HIT3");
return false;
} else {
System.out.println("Heres n : " + n);
return true;
}
}
Here's my loop. I know for sure that my number generator works though.
do {
num1 = generateNumber(p);
} while (isPrime(generateNumber(p)) == false);
do {
num2 = generateNumber(q);
} while (isPrime(generateNumber(q)) == false);
Don't test if the result of compareTo() equals -1. When you want to mean a < b, you should write a.compareTo(b) < 0. Always compare with 0, not any other constant.
Just realized what the issue was. I'm generating two different numbers in the loop and inside the loop. I was also incorrectly assigning the BigInteger incorrectly in the loop. I should be doing
num1 = new BigInteger(generateNumber(p).toString());
First, test if the number is 2 (if it is, then it is prime). Next, test if the number is divisible by 2 (if it is, then it is not prime). Next, iterate from 3 to the square root of the number in increments of 2 testing for divisibility with the original number (if it is, then it is not prime). Otherwise, the number is prime. Something like,
public static boolean isPrime(BigInteger n) {
final BigInteger two = new BigInteger("2");
if (n.equals(two)) {
return true;
}
if (n.mod(two).equals(BigInteger.ZERO)) {
return false;
}
for (BigInteger i = two.add(BigInteger.ONE); i.multiply(i).compareTo(n) < 1;
i = i.add(two)) {
if (n.mod(i).equals(BigInteger.ZERO)) {
return false;
}
}
return true;
}

Calculating best case run time complexity of recursive algorithm?

In class i have started learning how to calculate the run time complexity functions of various algorithms and am finding it difficult. I am trying to calculate the best case rune time complexity of my recursive algorithm below.
At the moment i am choosing my fundamental operation to be a comparison between the index of two chars, and assuming i am trying to find the path where my algorithm outputs a result as soon as possible, i am thinking this first comparison being false would lead my algorithm to do this if i am correct.
Would i be correct in thinking the best case run time complexity function for this algorithm would be t(n) = 1 and in taking the comparison of indexes as a fundamental operation?
public class StringShuffleTest {
public static boolean isOrderedShuffle(String a, String b, String c){
//variables for the size of Strings a, b and c.
int n = a.length();
int m = b.length();
int len = c.length();
//if the length of c is not the length of a + b, return false.
if (len != (n + m)){
return false;
}
//if String c contains String b as a substring, then remove String b from c and make m = 0.
//This statement avoids errors when dealing with Strings with very similar characters.
if (c.contains(b)){
c = c.replace(b, "");
m = 0;
}
//if the length of a or b is 0, and c equals a or b, return true, otherwise,
//return false.
if (n == 0 || m == 0){
if (c.equals(a) || c.equals(b)){
return true;
}
else
return false;
}
//if String a has length 1, remove a from String c and make String a empty.
if (n == 1){
c = c.substring(0, c.indexOf(a.charAt(0))) + c.substring(c.indexOf(a.charAt(0)) +1);
a = "";
return isOrderedShuffle(a, b, c);
}
//An ordered shuffle of two given strings, a and b, is a string that can be formed by interspersing
//the characters of a and b in a way that maintains the left-to-right order of the characters from each
//string.
//Recursive algorithm to determine if String c is an ordered shuffle of a and b.
else
if (c.indexOf(a.charAt(0)) >= 0){
int indexOfFirsta = c.indexOf(a.charAt(0));
int indexOfSeconda = c.indexOf(a.charAt(1));
if (indexOfFirsta <= indexOfSeconda){//Taking as fund operation.
c = c.substring(0, indexOfFirsta) + c.substring(indexOfFirsta +1);
a = a.substring(1, n);
System.out.println(a);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
else
if (c.indexOf(b.charAt(0)) >= 0){
int indexOfFirstb = c.indexOf(b.charAt(0));
int indexOfSecondb = c.indexOf(b.charAt(1));
if (indexOfFirstb <= indexOfSecondb){
c = c.substring(0, indexOfFirstb) + c.substring(indexOfFirstb +1);
b = b.substring(1, m);
System.out.println(b);
System.out.println(c);
return isOrderedShuffle(a, b, c);
}
}
}
return false;
}
public static void main(String[] args) {
System.out.println(StringShuffleTest.isOrderedShuffle("abc", "def", "abedcf"));
}
}

check if two integers sum to a third

Ok I'm doing this programming assignment and need a little help.
Here is the problem:
Given three ints, a b c, return true if it is possible to add two of the ints to get the third.
twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false
Here's the what I have gotten so far:
public boolean twoAsOne(int a, int b, int c) {
return a + b != c;
}
It keeps saying it is not fully correct and I do not know where I am going wrong.
The question asks if it is possible to add any two to get the remaining one. Your code tests only if the first two add to the third.
Thus, twoAsOne(3,1,2) should return true because 3 = 1 + 2; but you are only checking whether 3 + 1 = 2, which is false.
You're only checking one of the possibilities and, on top of that, you're checking it wrongly since you'll return false if a + b == c (because you're using the != operator).
I'm not going to do you homework for you, but the full list of possibilities is:
n1 = n2 + n3
n2 = n1 + n3
n3 = n1 + n2
It should be a simple matter: the result should be true if any of those is true. Otherwise the result should be false.
Or, to provide even a more obvious clue: it should be true if one or more of those conditions are met. Else it should be false.
I don't know how much more obvious I can make it without writing the code for you :-)
Update: And now that more than enough time has probably elapsed to make the homework point moot, here's my solution:
public boolean twoAsOne (int n1, int n2, int n3) {
if (n1 == n2 + n3) return true;
if (n2 == n1 + n3) return true;
if (n3 == n1 + n2) return true;
return false;
}
Although those last two lines could be replaced with:
return (n3 == n1 + n2);
I prefer the (to me, anyway) more readable version.
Besides the answers provided by itowlson and Pax, since you are dealing with ints, there is a possibility that they will overflow, e.g.
Integer.MAX_VALUE + 1 == Integer.MIN_VALUE
Which is not mathematically true
You may want to check this kind of scenarios to make your program complete.
Your code only takes into consideration the sum of int a and int b. The solution requires all possibilities to be covered i.e. "sum of int a and int c" and "sum of int b and int c". Refer to the code mentioned below, hope it helps!
public boolean twoAsOne(int a, int b, int c) {
return ((a + b == c) || (b + c == a) || (c + a == b));
}
Dude I hope you got the answer by now... if you haven't
public boolean twoAsOne(int a, int b, int c) {
return ((a+b==c) || (a+c==b) || (b+c==a));
}
I might be very late yet I have minimized it. twoAsOne
public boolean twoAsOne(integer a, integer b, integer c){
return ((a+b) == c ? true : (a+c) == b ? true : (b+c == a)? true : false);
}
package get_third;
public class Get_third {
int a , b ,c ;
boolean third_value(int a , int b , int c){
if(a+b==c||b+c==a||c+a==b)
{
return true;
}
else
return false ;
}
public static void main(String[] args) {
Get_third obj =new Get_third();
System.out.println(obj.third_value(1, 2, 3));
System.out.println(obj.third_value(3, 1, 2));
System.out.println(obj.third_value(3, 2, 2));
}
}
// start
public boolean twoAsOne(int a, int b, int c) {
if (a + b == c) {
return true;
}
else if (a + c == b) {
return true;
}
else if (b + c == a) {
return true;
}
else {
return false;
}
}
// end

Categories

Resources