jeudi 2 février 2017

Eucild Algorithm Java

so my teacher in my Begininer posted for us to understand while loops and i do understand the mechanics of the while loop however i am stuck at understanding how the output for this program produces the GCD ?

Could some one help explain how the code produces the GDC?

Thank you

 import java.util.Scanner;

// Output GCD of user-input numA and numB

public class GCDCalc {
public static void main(String[] args) {
  Scanner scnr = new Scanner(System.in);
  int numA = 0; // User input
  int numB = 0; // User input

  System.out.print("Enter first positive integer: ");
  numA = scnr.nextInt();

  System.out.print("Enter second positive integer: ");
  numB = scnr.nextInt();

  while (numA != numB) { // Euclid's algorithm
     if (numB > numA) {
        numB = numB - numA;
     }
     else {
        numA = numA - numB;
     }
  }

  System.out.println("GCD is: " + numA);

  return;

} }

Aucun commentaire:

Enregistrer un commentaire