×

Relatively Prime in Java

In this article, you will be very well equipped with a knowledge of a relatively prime number and also Java programs to determine whether a given integer is a relatively prime number or not. Both academics and interviews for Java coding positions regularly question about the reasonably prime number programs.

First of all, lets us recall about the prime number that we have learnt long ago in our school.

Prime Number

A prime number is a number that can be divided only by 1 and by the number itself. let us consider a number 'p'. Divide the number p by all integer q values that are smaller than or equal to the square root of p to determine if a given number is a prime or not. P is a composite number if it can be divided neither by itself nor by one.

Let us understand it with a very simple example.

Consider number 10.

The number 10 can be divisible by 1,2,5,10.

Also consider a number 11.

The number 11 can only be divisible by 1 and the number 11 itself.

Now as we have acquired the general knowledge about the prime numbers, now lets move on to the relatively prime numbers in java.

Relatively Prime Numbers

The numbers that only have the number 1 as their common divisor are referred to as relatively prime numbers. Therefore, 1 is the largest common divisor of both numbers. Coprime numbers are another term for relatively prime numbers.

Let us understand it through a simple example.

Consider numbers 16 and 17

The factors of 16 are (1,2,4,8,16)

The factors of 17 are (1,17)

From the above observation, the numbers 16 and 17 have 1 as their greatest common divisor. Therefore, those two numbers are considered as relatively prime numbers.

Now lets us understand the concept of relatively prime numbers by a program. Go through the program flow to understand it.

File name: CoPrime.java

import java.util.ArrayList;  
import java.util.Collection;  
import java.util.List;  
import java.util.Scanner;  
public class CoPrime   
{  
    /* This is the method for finding and showing the factore of the given two numbers. */  
    static List<Integer> printDiv(int n)  
    {  
        List<Integer> lstDiv= new ArrayList<>();  
        int maxD = (int)Math.sqrt(n);  
        for (int i=1; i<=maxD; i++)  
        {  
            if (n%i==0)  
            {  
                /* Displays only once if the factors are same for both */  
                if (n/i == i)  
                    lstDiv.add(i);  
                  
                // In this else block it will display both the numbers separately  
                else   
                {  
                    lstDiv.add(i);  
                    lstDiv.add(n/i);  
                }  
            }  
        }  
        return lstDiv;  
    }  
      
   
    public static void main(String[] ar)  
    {  
        Scanner sc= new Scanner(System.in);  
        /*Taking the input greater than 1 from the user. */  
        System.out.println("Enter the first number that must be greater than zero:");  
        int num1= sc.nextInt();  
        /* Taking another input from user that shound not match the first number. */  
        System.out.println("Enter the second number that must be greater than zero and should not match the first number:");  
        int num2= sc.nextInt();  
        /* Computing the factors of the first number */  
        System.out.println("Factors of "+num1+" are: ");  
        List<Integer> l1= printDiv(num1);  
        System.out.println(l1);  
        /* Computing the factors of the second number */  
        System.out.println("The factors of "+num2+" are: ");  
        List<Integer> l2= printDiv(num2);  
        System.out.println(l2);  
          
        /* Finding common elements in both the lists */  
        l1.retainAll(l2);  
          
        /* Verify if numbers are relative primes */  
        if(l1.size()==1 && l1.get(0)==1)  
        {  
            System.out.println("The first number "+num1+" and the second number "+num2+" are relatively prime numbers.");  
        }  
        else  
            System.out.println("The first number "+num1+" and the second number "+num2+" are not relatively prime numbers.");  
    }  
      
}  

Output

Enter the first number that must be greater than zero:
50
Enter the second number that must be greater than zero and should not match the first number:
51
Factors of 50 are:
[1, 50, 2, 25, 5, 10]
The factors of 51 are:
[1, 51, 3, 17]
The first number 50 and the second number 51 are relatively prime numbers.

The above is an output when two numbers are relatively prime numbers.

Enter the first number that must be greater than zero:
20
Enter the second number that must be greater than zero and should not match the first number:
22
Factors of 20 are:
[1, 20, 2, 10, 4, 5]
The factors of 22 are:
[1, 22, 2, 11]
The first number 20 and the second number 22 are not relatively prime numbers.

The above is the output when the two numbers are not relatively prime numbers.

Two numbers - num1 and num2 - are provided from the users in the Java code above. The method printDiv() is used to determine the factors of these two numbers, and if none of them has any comparable factors apart from 1, the numbers are considered relatively prime numbers. Else the numbers shall be considered as not relatively prime numbers.


Related Topics

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Java Command Line Arguments

Java command line arguments Command line argument is an input or argument to the program when you run the program. In Java, we can take the inputs from the console, and...

2 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Advanced Java skills

These were some of the contemporary talents that a Java developer should master in efforts to progress in the era of science in 2022. A database such as MySQL, a...

4 minutes read.

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Program to Reverse a Number in Java

In order to reverse a number, the digit in the first place must be swapped with the digit in the final position, the second digit with the second-to-last digit, and...

3 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

How to Calculate Time Difference Between Two Dates in Java?

Date is being used extensively in Java to calculate date differences. While constructing an application, the date of joining an organisation, admission date, appointment date, and others might be included....

4 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Java Beans

It is a Java class, It follows conventions they are: It must have a no-arg constructorIt must be serializable.It must provide the methods to get and set the properties Uses Of Java...

3 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.

Minimum XOR value pair in Java

In this section, you will discuss about minimum XOR value pair in Java. The objective is to enforce a value that indicates the least XOR values of the two numbers from...

4 minutes read.

How to get ASCII value of char in Java

Introduction: On this application, you will learn how to find and show the ASCII value of char in Java. That is done with the use of type-casting and also everyday...

4 minutes read.