In: Computer Science
Create a program that asks the user for two positive integers. If the user's input for either integer is not positive (less than or equal to 0), re-prompt the user until a positive integer is input. You may assume that all inputs will be integers.
Print out a list, ascending from 1, of all divisors common to both integers. Then, print out a message stating whether or not the numbers are "relatively prime" numbers. Two positive integers are considered relatively prime if, and only if, the only common divisor they have is 1.
For example, if the user inputs 8 and 12 the output should be:
Common divisors of 8 and 12:
1
2
4
8 and 12 are not relatively prime.
If the user inputs 8 and 9, on the other hand, the output should be:
Common divisors of 8 and 9:
1
8 and 9 are relatively prime.
Starter Code:-
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); //Scanner to get user
input
//TODO
//Complete the program
}
}
Screenshot of the Code:
Sample Output:
Code to Copy:
import java.util.Scanner;
public class RelativelyPrime {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in); //Scanner to get user
input
//Prompt the user for input.
System.out.print("Enter the first positive integer: ");
int pint1 = scnr.nextInt();
//Validate the input.
while (pint1 <= 0) {
System.out.print("Error. Enter a positive integer: ");
pint1 = scnr.nextInt();
}
//Prompt the user for input.
System.out.print("Enter the second positive integer: ");
int pint2 = scnr.nextInt();
//Validate the input.
while (pint2 <= 0) {
System.out.print("Error. Enter a positive integer: ");
pint2 = scnr.nextInt();
}
//Display the message.
System.out.println("Common divisors of " + pint1 + " and " + pint2
+ ":");
//Declare the variable.
int flag = 0;
//Iterate from 1 to first positive integer.
for (int iter = 1; iter <= pint1; iter++) {
//Check for relatively prime condition.
//Print the number and update the flag.
if (pint1 % iter == 0 && pint2 % iter == 0) {
System.out.println(iter);
flag++;
}
}
//Check the flag print the final result.
if (flag > 1) {
System.out.println(pint1 + " and " + pint2 + " are not relatively
prime.");
} else {
System.out.println(pint1 + " and " + pint2 + " are relatively
prime.");
}
//Close the scanner object.
//scnr.close();
}
}