I am having trouble understanding how to program below works and I would appreciate someone explaining to me how exactly it runs.
public static void main(String[] args) {
//Enter two number whose GCD needs to be calculated.
Scanner scanner = new Scanner(System.in);
// Title of what program will do
System.out.println("GCD Finder");
System.out.println("");
// Here user is instructed to enter the numbers
System.out.println("Please enter first number: ");
int number1 = scanner.nextInt();
System.out.println("Please enter second number: ");
int number2 = scanner.nextInt();
// The numbers are then calculated using findGCD.
System.out.println("GCD of two numbers " + number1 +" and " + number2 +" is : " + findGCD(number1,number2));
}
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
// Returns the two numbers
return findGCD(number2, number1%number2);
}
This part below is specifically what I am having trouble understanding. Please do not hesitate to explain in detail, I want to understand it fully. Thank you for your time.
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
// Returns the two numbers
return findGCD(number2, number1%number2);
}
So the part you are in particular struggling with:
// A function which returns the greatest common divisor.
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
// Returns the two numbers
return findGCD(number2, number1%number2);
}
This is a recursive function, which is i imagine what is causing you difficulty. To better understand recursive functions in general perhaps read this: http://www.python-course.eu/recursive_functions.php Don't worry that it uses python as an example.
In this case in particular the function will return number 1 when number 2 is 0. if number two isnt zero then it will call the function again with number2 being the remainder of number1 / number2, otherwise known as the modulus % https://en.wikipedia.org/wiki/Modulo_operation.
You could write the function in a while loop aswell:
//PSEUDOCODE WATCH YOURSELF
private static int findGCD(int n1, int n2) {
int result = 0;
while(true) {
if(n2 == 0) {
return result;
}
result = n1;
n1 = n2;
n2 = result-n2;
}
}
Hope that helps a little? Or at least doesn't make anything more confusing.