Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Dec 2011
    Location
    abuja
    Posts
    18
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Gcd? A challenge

    Can someone help me re-program this greatest common divisor program to solve for prime numbers to give an output of 1 OR such that a and b output 1.

    import java.util.Scanner;
    public class Euclid
    {
    public static void main(String[] args){
    Scanner sc=new Scanner(System.in);
    int a=getPositive("first", sc);
    int b=getPositive("second", sc);
    int d=Math.min(a, b);
    while(true){
    if(a%d==0&&b%d==0)
    break;
    d--;
    }
    System.out.printf("gcd for %d and %d is %d%n", a, b,d);
    }
    static int getPositive(String instruction, Scanner sc){
    int number=0;
    do{
    System.out.printf("enter a %s positive integer", instruction);
    number=sc.nextInt();
    while(number<0);
    return number;
    }
    }

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,978
    Thanks
    4
    Thanked 2,659 Times in 2,628 Posts
    I posted a recursive version of GCD here: Java Questions


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •