Javatpoint Logo
Javatpoint Logo

Relatively Prime in Java

In this section, we will learn what is a relatively prime number and also create Java programs to check if the given number is a relatively prime number or not. The relatively prime number program is frequently asked in Java coding interviews and academics.

Prime Number

A prime number is a number that only has two divisors, 1 and the number itself. To check if a number is prime or not, divide the number p by all the smaller or equal to the square root of p, integer q values. If the number p is divisible by other numbers than itself or 1, it is a composite number.

Prime Number Example

  1. Consider 14. It is divisible by {1, 2, 7, 14}
    Therefore, it is a composite number.
  2. Consider 17. It is divisible by {1, 17}
    Therefore, it is a prime number.

Relatively Prime Numbers

Relatively prime numbers are the numbers that don't share any common divisors other than 1. It means that the greatest common divisor for both numbers is 1.

Relatively prime numbers are also called coprime numbers.

Example of a Relative prime number

Consider 14 and 15.

Factors of 14 are {1, 2, 7, 14}

Factors of 15 are {1, 15}

Both numbers have 1 as their greatest common divisor. Hence, 14 and 15 are relatively prime numbers.

Relative Prime Number Java Program

RelativePrimeExample.java

Output:

Please enter the first number greater than zero:
7
Please enter the second number greater than zero and not equal to first number:
27
The factors of 7 are: 
[1, 7]
The factors of 27 are: 
[1, 27, 3, 9]
7 and 27 are relative primes.

In the above Java code, two numbers are accepted from user, num1 and num2. The factors of these two numbers are identified using the method printDiv() and if neither of them has matching factors other than 1, the numbers are said to be relatively prime.


Next TopicJava Modulo





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA