I was trying to write the code of Euclids algorithm and I found some code online which works out the greatest common divisor for two numbers entered. Here it is
else {
return gcd(b, a % b);
}
However, I don't quite get how it gets me the greatest common divisor. I understand how Euclid's algorithm works on paper but not this.
To my eyes the above code should return the modulus a of b, so if "a" were 1071 and "b" was 462 it would return 147 however the above code returns 21. How does the first b in <code>gcd(b, a % b); affect the output?
Here's the entire code:
package algorithms;
import java.util.Scanner;
public class Question3 {
private static Scanner input=new Scanner(System.in);
public static void main(String[] args) {
//simple input statements to get the numbers of the user
System.out.print("Please input the first number to be worked on= ");
double a=input.nextDouble();
System.out.print("Please input the second number to be worked on= ");
double b=input.nextDouble();
//call the method in which the calculations are done
double commondiv=gcd(a,b);
//print out the the common divisor
System.out.print("The Common Divisor of "+ a +" and "+ b + " is "+commondiv);
//System.out.print(b);
}
public static double gcd(double a, double b){
//an if statement will allow for the program to run even if
//a is greater than b
if (a>b){
//if the input b is equal to zero
//then the input a will be returned as the output
//as the highest common divisor of a single number is itself
if (b == 0){
return a;
}
//this returns the greatest common divisor of the values entered
else{
return gcd(b, a % b);
}
}
else if (a<b){
if (a == 0){
return b;
}
else{
return gcd(a, b % a);
}
}
return 0;
}
Please See the Following Explanation for iterations :
In first Iteration
a = 1071 and b = 462
a >b so
gcd(b,a % b) which is gcd(462,147)
Again a>b is true as a = 462,b = 147 so
gcd(147,21)
a>b is true as a = 147, b = 21 so
gcd(21,0)
a>b is true as a = 21 ,b = 0
Now b == 0 is true
return a i.e. 21
Related
Basically is about the binary numbers, the user needs to input two random numbers, both numbers will be added, and the addition of those two numbers only needs to have ones and zeros for example 5+6==11 OR 55+55=110, then throw a message saying “the addition only has 1’s and 0’s, otherwise for example 25+46=71 or 575+575=1150 then a message saying the addition does not have only 1’s and 0’s.
I just started learning java and i can’t find anything helpful for this problem, i already know the conditionals if only have ones and zeros or not.
this is the code i already have, but when i input for example 575+575+1150 says only has 1's and 0's, i guess i cant use .contains for this.
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n1;
int n2;
int add;
System.out.print("Input Number 1: ");
n1=read.nextInt();
System.out.print("Input number 2: ");
n2=read.nextInt();
System.out.println();
add=n1+n2;
System.out.println("The addition is = "+add);
String S = String.valueOf(add);
if(S.contains("1") && S.contains("0")) {
System.out.print("The addition only has 1's and 0's");
}
else{System.out.print("The addition does not only have 1's and 0's");}
}
}
I saw your code and and the resultant sum 1150 does contain 1's and 0's.
s.contains(x);
This function only checks if the string contains the value x or not. Since "1150" contains both 1's and 0's therefore your function prints the wrong output.
One way of solving this problem would be to add the two numbers and then check the resultant sum digit by digit. You can make a function that will do that for you.
public void checkOnesAndZeros(int resultantSum) {
while (resultantSum > 0) {
int remainder = resultantSum % 10;
if(remainder != 1 && remainder != 0) {
System.out.println("The addition does not have only 1’s and 0’s.");
return;
}
resultantSum = resultantSum / 10;
}
System.out.println("The addition only has 1’s and 0’s");
}
One way is to create a String using the added numbers and iterating through the characters.
public static boolean isResultBinary(int n1, int n2) {
String sum = n1 + n2 + "";
for (int i = 0; i < sum.length(); i++) {
char c = sum.charAt(i);
if (c != '1' && c != '0') return false;
}
return true;
}
Here's a method I wrote, it checks every character c to see if it is either '0' and '1'. If a character is not either one, the method will return false. Otherwise, it'll loop through the whole string and return true.
To get your desired output, use this method like this in within your main method:
if (isResultBinary(n1, n2)) System.out.println("The addition only has 1's and 0's");
else System.out.print("The addition does not only have 1's and 0's");
Here is another take on the question.
convert the sum to a string and then try and parse it as binary.
if it isn't binary, an exception will be thrown, so return false.
otherwise return true.
int[] sums = { 110, 120, 10111, 250, 203, 2011, 1110111 };
for (int n : sums) {
System.out.printf("%8s - %s%n", n,
"is " + (checkOnesAndZeros(n) ? "" : "not ")
+ "all ones and zeros");
}
prints
110 - is all ones and zeros
120 - is not all ones and zeros
10111 - is all ones and zeros
250 - is not all ones and zeros
203 - is not all ones and zeros
2011 - is not all ones and zeros
1110111 - is all ones and zeros
The method
public static boolean checkOnesAndZeros(int resultantSum) {
try {
Integer.parseInt(Integer.toString(resultantSum), 2);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Guys I found this code in online,used to find L.C.M of the two numbers but I couldn't understand the gcd() function.
when I try with a input a = 2,b = 3.It's showing 6 but when I do debugging myself I can't get the answer. I am struct here if (a == b) return a;
can you please help me to understand it's functionality. Please update with step by step functions
// Java program to find LCM of two numbers.
class Test
{
// Recursive method to return gcd of a and b
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0 || b == 0)
return 0;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
// method to return LCM of two numbers
static int lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
// Driver method
public static void main(String[] args)
{
int a = 15, b = 20;
System.out.println("LCM of " + a +" and " + b + " is " + lcm(a, b));
}
}
From Wikipedia (https://en.wikipedia.org/wiki/Greatest_common_divisor):
In mathematics, the greatest common divisor (gcd) of two or more integers, which are not all zero, is the largest positive integer that divides each of the integers. For example, the gcd of 8 and 12 is 4.
Using Euclid's algorithm
Formally the algorithm can be described as:
gcd(a,0)=a
gcd(a,b)=gcd(b,a mod b)
where
a mod b = a - b [ a / b ]
If the arguments are both greater than zero then the algorithm can be written in more elementary terms as follows:
gcd(a,a)=a
gcd(a,b)=gcd(a-b,b), if a > b
gcd(a,b)=gcd(a,b-a), if b > a
I'm trying to write a method that will calculate if two numbers are relatively prime for an assignment. I'm primarily looking for answers on where to start. I know there is a method gcd() that will do a lot of it for me, but the assignment is pretty much making me do it without gcd or arrays.
I kind of have it started, because I know that I will have to use the % operator in a for loop.
public static boolean relativeNumber(int input4, int input5){
for(int i = 1; i <= input4; i++)
Obviously this method is only going to return true or false because the main function is only going to print a specific line depending on if the two numbers are relatively prime or not.
I'm thinking I will probably have to write two for loops, both for input4, and input5, and possibly some kind of if statement with a logical && operand, but I'm not sure.
Well in case they are relatively prime, the greatest common divider is one, because - if otherwise - both numbers could be devided by that number. So we only need an algorithm to calculate the greatest common divider, for instance Euclid's method:
private static int gcd(int a, int b) {
int t;
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a;
}
And then:
private static boolean relativelyPrime(int a, int b) {
return gcd(a,b) == 1;
}
Euclid's algorithm works in O(log n) which thus is way faster than enumerating over all potential divisors which can be optimized to O(sqrt n).
Swift 4 code for #williem-van-onsem answer;
func gcd(a: Int, b: Int) -> Int {
var b = b
var a = a
var t: Int!
while(b != 0){
t = a;
a = b;
b = t%b;
}
return a
}
func relativelyPrime(a : Int, b: Int) -> Bool{
return gcd(a: a, b: b) == 1
}
Usage;
print(relativelyPrime(a: 2, b: 4)) // false
package stack;
import java.util.Scanner; //To read data from console
/**
*
* #author base
*/
public class Stack {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in); // with Scanner we can read data
int a = in.nextInt(); //first variable
int b = in.nextInt(); //second variable
int max; // to store maximum value from a or b
//Let's find maximum value
if (a >= b) {
max = a;
} else {
max = b;
}
int count = 0; // We count divisible number
for (int i=2; i<=max; i++) { // we start from 2, because we can't divide on 0, and every number divisible on 1
if (a % i == 0 && b % i==0) {
count++; //count them
}
}
if (count == 0) { // if there is no divisible numbers
System.out.println("Prime"); // that's our solutions
} else {
System.out.println("Not Prime"); //otherwise
}
}
}
I think that, this is the simple solution. Ask questions in comments.
I am wanting to ask the user to input three numbers and then have program calculate the GCD using Euclid's algorithm all the while using recursion.
My code right now implements two input numbers. I understand the approach of calculating the GCD of a and b, and calling it result d. Then using the third input (c) and d to find the GCD and essentially repeating Euclid's algorithm again; I am not sure how to implement this in code.
import java.util.Scanner;
public class RecursionDemo {
public static void main (String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = userInput.nextInt();
System.out.println("Enter second number: ");
int b = userInput.nextInt();
System.out.println("GCD is: " + gCd(a, b));
}
public static int gCd(int a, int b) {
if(b == 0){
return a;
}
return gCd(b, a%b);
}
}
The part that is really throwing me off is using recursion to solve my problem.
So far I know I need to implement:
System.out.println("Enter third number: ");
int c = userInput.nextInt();
d = //Not sure here
//And then modify my recursion method to find GCD.
Any help or suggestions would greatly be appreciated!
d = gCd (a, b);
System.out.println("GCD is: " + gCd(d, c));
Note that you may call your gCd function with any two arguments, not just a and b. For better understanding and less confusion, you may want to rename its arguments, like the following:
public static int gCd(int x, int y) {
if(y == 0) {
return x;
}
return gCd(y, x%y);
}
So, first you call it with x = a and y = b to find GCD of a and b. Store the result into new variable d. After that, you call it again with x = d which is in turn GCD of a and b, and y = c. Thus you get the GCD of all the three numbers.
The gcd method can be iterated to obtain the gcd of a larger set of numbers.
For example:
gCd(a, b, c) = gCd( gCd(a, b), c)
and
gCd(a, b, c, d) = gCd( gCd(a, b, c), d) so then
gCd(a, b, c, d) = gCd( gCd( gCd(a, b), c), d)
Easy, specific solution:
System.out.println("GCD is: " + gCd( gCd(a, b), c) );
However, if you'll notice, there is recursion going on. I've created a method that takes an array of integers as an input. It will work for an array of size three, or any size. Here are the methods:
/* returns gcd of two numbers: a and b */
public static int gCd(int a, int b) {
if (b == 0) {
return a;
}
return gCd(b, a%b);
}
/* returns gcf of an array of numbers */
public static int gCd(int[] numbers)
{
int result = numbers[0]; // first number
for(int i = 1; i < numbers.length; i++) {
result = gCd(result, numbers[i]); // gcf of itself and next #
}
return result;
}
So, to relate it to your code:
Scanner userInput = new Scanner(System.in);
System.out.println("Enter first number: ");
int a = userInput.nextInt();
System.out.println("Enter second number: ");
int b = userInput.nextInt();
System.out.println("Enter third number: ");
int c = userInput.nextInt();
// you can do this
System.out.println("GCD is: " + gCd( gCd(a, b), c) );
// or you can do this
int[] numbers = {a, b, c};
int d = gCd(numbers);
System.out.println("GCD is: " + d);
Sample input/output:
Enter first number:
12
Enter second number:
18
Enter third number:
30
GCD is: 6
GCD is: 6
I am trying to write a code that prompts the user for three numbers and the program is supposed to say what number is the greatest. I didn't want to do a bunch of "System.out.print" in the if and else if statements. The error according to the debugger is that "greatest" and "greatest1" have not been initialized.
import java.util.Scanner;
public class number1
{
public static void main(String[] args)
{
double a, b, c;
double greatest, greatest1;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter one number :");
a = keyboard.nextDouble();
System.out.print("Enter another number :");
b = keyboard.nextDouble();
System.out.print("Enter a third number :");
c = keyboard.nextDouble();
if(a > b && a > c) {
greatest = a;
} //end of if statement
else if(b > a && b > c){
greatest = b;
}
else if(c > a && c > b) {
greatest = c;
}
else if(a==b && c < a) {
greatest = a;
greatest1 = b;
}
else if(a==c && b < a) {
greatest = a;
greatest1 = c;
}
else if(b==c && a < b) {
greatest = b;
greatest1 = c;
}
else {
System.out.print("All of the numbers are greatest");
}
System.out.print("The greatest number is: " +greatest+ "and" +greatest1);
}
}
Since, the others have already point out the problem. I am going to point out that you can find the biggest number out of three number by just doing :
biggest = Math.max(a, Math.max(b,c));
You can replace all the conditionals in your code.
Imagine that you want the max of a set of integers (e.g., an array of ints). You can do something like:
biggest = array[0]; // initialize max to the first number of the set
iterate over the set and checking the max:
for(int i = 1; i < array.size; i++)
biggest = Math.max(biggest,array[i]);
or with Java Streams:
Arrays.stream(array).max().getAsDouble()
You can also make your own max function, for your case can the following:
public double maxDouble (double a, double b){
if(a > b) return a;
else return b;
}
You can read here more detailed information about the Math class and their methods (such as public static double max(double a,double b).
To fix this, you need to make sure greatest and greatest1 are always assigned to a value. What would happen if it went into this code block:
if (a > b && a > c) {
greatest = a;
} //end of if statement
greatest1 would not be assigned so when it printed it out in the last statement that says
System.out.print("The greatest number is: " + greatest + "and" + greatest1);
It's giving you an error.
Another tip: If you press enter after entering each number, you should read the newline \n after you read each number.
E.g.
a = keyboard.nextDouble();
Should be changed to
a = keyboard.nextDouble();
keyboard.nextLine();
etc.
Take input from keyboard and create a double array and then try below code.
double dblArray[] = {24.0,40.2,38.9};
Arrays.sort(dblArray);
System.out.print("The greatest number is: " +dblArray[dblArray.length-1]+ " and " +dblArray[dblArray.length-2]);
You can print n greatest numbers.
As a general hint: Initialize with 0:
double greatest = 0;
double greatest1 = 0;
But be warned, in your case this indicates an error in your code logic.
Fix that logic, otherwise the result will be 0, which can be wrong.