HydratedDeer
HydratedDeer

Reputation: 43

Printing Common Divisors of Inputted Positive Integers

I need to print the common divisors between two positive integers that were entered. They need to be printed in ascending order. If they are relatively prime, "1" needs to be printed. The code I have here is nowhere near correct. I'm really confused on how to use the loops properly while keeping it in ascending order.

Sample input:

Integer a: 8 Integer b: 12

Sample Output:

Common divisors of 8 and 12:

1

2

4

8 and 12 are not relatively prime.

Alternate Input:

Integer a: 8 Integer b: 9

Common divisors of 8 and 9:

1

8 and 9 are relatively prime.

import java.util.Scanner;

 public class RelativelyPrime {
      public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);  

 int num1 = scnr.nextInt();
  int num2 = scnr.nextInt();
  System.out.println("Common divisors of " + num1 + " and " + num2 + ":");

  int div1 = 0;
  int div2 = 0;
  int same = 0;
  for (int i=1;i<=num1;i++) {
    while (div1 <= num1) {
      div1 = num1/i;
    }
    while (div2 <= num2) {
      div2 = num2/i;
    }
    if (div1 == div2) {
      div1 += same;
      System.out.println(same);
      System.out.println(num1 + " and " + num2 + " are not relatively prime.");
    }
    if (div1 != div2) {
      System.out.println(1);
      System.out.println(num1 + " and " + num2 + " are relatively prime.");
    }
    }
}
}

Upvotes: 0

Views: 111

Answers (2)

Habib Mhamadi
Habib Mhamadi

Reputation: 779

Scanner input = new Scanner (System.in);
num1 = input.nextInt();
num2 = input.nextInt();
List<Integer> list = new ArrayList<>();

for(int i=0; i<=Math.min(num1,num2);i++){
 if(num1%i==0 && num2%i==0){
 list.add(i);
}
  }

System.out.println("Divisors:");

for(int a : list){
 System.out.println(a);  }

if(list.size()<2){
 System.out.print("Not Relatively Prime");  }

else { System.out.print("Relatively Prime");}

Upvotes: 0

theincrediblethor
theincrediblethor

Reputation: 448

You can try something simple like the below:

import java.util.Scanner;

 public class RelativelyPrime {
      public static void main(String[] args) {
          Scanner scnr = new Scanner(System.in);  
          int num1 = scnr.nextInt();
          int num2 = scnr.nextInt();
          System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
          for(int i = 1; i<= Math.min(num1,num2); i++){
            if(num1%i==0 && num2%i==0) {
               System.out.println(i);
            }
          } 
       }
}

Upvotes: 1

Related Questions