×

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input array. A note subsequence is created by selecting one or more elements at a time from an array.

Brute Force Approach

According to this method, we will compute each subsequence of the input array and store them in an array list. After that compute the GCD for each subsequence contained in the array list, we will group them into sets. The size of the set will be our response because the set only consists of distinct components. Recursion will be used to find the subsequences. Take note of the programme below.

GCDDiff1.java

// importing important required packages
import java . util . ArrayList ;  
import java . util . Set ;  
import java . util . HashSet ;  
 // public class with name GCDDiff1 is created
public class GCDDiff1  
{  
// arraylist with name arrlist is created
ArrayList <ArrayList<Integer>>  arrlist = new ArrayList <ArrayList<Integer>> ( ) ;  
Set<Integer> set = new HashSet<Integer> ( ) ;  
  // public method to finf sub sequence
public void find_sub_seq ( int arr1 [ ] , int size , int i1 , ArrayList < Integer >  tempvalue )   
{  
if ( i1 >= size )  
{  
  


ArrayList < Integer > t1 = new ArrayList < Integer > ( ) ;  
for ( int idx1 = 0 ; idx1 < tempvalue . size ( ) ; idx1++ )  
{  
t1 . add ( tempvalue . get ( idx1 ) ) ;  
}  
arrlist .add( t1 ) ;  
return ;  
}   
tempvalue . add ( arr1 [ i1 ] ) ;  
find_sub_seq ( arr1 , size ,  i1 + 1 , tempvalue ) ;  
int index1 = tempvalue . size() – 1 ;  
tempvalue . remove ( index1 ) ;  
find_sub_seq ( arr1 , size , i1 + 1 , tempvalue ) ;  
}  
  
// public method to find gcd
public int find_GCD ( int num1 ,  int num2 )  
{  
if ( num1 == 0 )  
{  
return num2 ;  
}  
return find_GCD ( num2 % num1 , num1 ) ;  
}  
// public method to find gcd of the subsequences
public void find_GCD_sub_seq ( ArrayList < Integer > arrlist1 )  
{  
// if array size is 0 return 
if ( arrlist1 . size ( )  == 0 )  
{  
return ;  
}  
// if array size is 1 return
if ( arrlist1 . size ( )  == 1 )  
{  
set . add ( arrlist1 . get ( 0 ) ) ;  
return ;  
}  
// assigning two integer variables to first two values of 
int t11 = arrlist1 . get ( 0 ) ;  
int t22 = arrlist1 . get( 1 ) ;  
int tt = find_GCD ( t11 , t22 ) ;  
for ( int i1 = 2; i1 < arrlist1 . size ( ) ; i1++ )  
{  
tt = find_GCD ( tt , arrlist1 . get ( i1 ) ) ;  
}   
Set . add ( tt ) ;  
}  
public void find_GCD_Util()  
{  
int size1 = arrlist . size();  
  
for ( int i1 = 0 ; i1 < size1 ; i1++ )  
{  
find_GCD_sub_seq ( arrlist . get ( i1 ) ) ;  
}  
}
// main section where execution of the program starts
public static void main ( String args [ ] )  
{  


GCDDiff1 object1 = new GCDDiff1 ( ) ;  
int inarr [ ] = {4 , 6 , 8 } ;  
int size = inarr . length ;  
ArrayList < Integer > tempvalue = new ArrayList < Integer > ( ) ;  
object1 . find_sub_seq ( inarr , size , 0 , tempvalue ) ;  
object1 . find_GCD_Util ( ) ;  
System . out . println ( " For the input array: " ) ;  
for ( int i1 = 0 ; i1 < size ; i1++ )  
{  
System . out . print ( inarr [ i1 ] + "  " ) ;  
}  
System . out . println ( ) ;  
System . out . println ( " The total number of unique GCDs is: " + object1 . set . size ( ) ) ;  
System . out . println ( ) ;  
object1 . set = new HashSet < Integer > ( ) ;  
object1 . arrlist = new ArrayList < ArrayList < Integer > > ( ) ;  
 
int inarr1 [ ]  = {3 , 6 , 9 } ;  
size = inarr1 . length ;  
tempvalue = new ArrayList < Integer > ( ) ;  
object1 . find_sub_seq ( inarr1 , size , 0 , tempvalue ) ;  
object1 . find_GCD_Util ( ) ;  
System . out . println ( " For the input array: " ) ;  
for( int i1 = 0; i1 < size; i1++ )  
{  
System . out . print ( inarr1 [ i1 ] + " " ) ;  
}  
System . out . println ( ) ;  
System . out . println ( " The total number of unique GCDs is: " + object1 . set . size ( ) ) ;  
}  
}  

Output

GCD of Different SubSequences in Java

Effective Approach:

We are able to perform the optimization using the greedy method. The GCD of any two numbers, n1 and n2, must lie between 1 and a maximum of ( n1 , n2 ) , and the same principle holds true for any sequence with more than two members. The GCD will always fall between [ 1 , M ] if the highest element in a subsequence is M. As a result, if we iterate between 1 and M, and any integer in the range is a factor of one of the array's elements, we can display that element as one of the GCD's results.

GCDDiff2.java

import java . util . ArrayList ;  
import java . util . Set ;  
import java . util . HashSet ;  
// public class 
public class GCDDiff2   
{  
public int find_GCD ( int num1 , int num2 )  
{  
// if num1 is 0 return num2
if ( num1 == 0 )  
{  
return num2 ;  
}  
return find_GCD ( num2 % num1, num1 ) ;  
}  
public int find_GCDs_Sub_seq ( ArrayList < Integer > arrList )  
{ 
ArrayList < Integer > ans = new ArrayList < Integer > ( ) ;  


HashSet < Integer > hs1 = new HashSet < Integer > ( ) ;  
for ( int i1 = 0 ; i1 < arrList . size ( ) ; i1++ )  
{  
hs1 . add ( arrList . get ( i1 ) ) ;  
}  
  
int Maximum = Integer . MIN_VALUE ;  
for ( int i1 = 0; i1 < arrList . size ( ) ; i1++ )  
{  
if ( arrList . get ( i1 ) > Maximum )  
{  
Maximum = arrList . get ( i1 ) ;  
}  
}     
for ( int j1 = 1 ; j1 <= Maximum ; j1++ )  
{  
int compute_GCD = 0 ;  
for ( int k1 = j1 ; k1 < Maximum + 1 ; k1 += j1 )  
{  
if  ( hs1 . contains ( k1 ) )   
{  
compute_GCD = find_GCD (compute_GCD , k1 ) ;  
}  
}  
if ( compute_GCD == j1 )  
{  
ans . add ( j1 ) ;  
}  
}  
return ans . size ( ) ;  
} 
// main section of the program where execution starts
public static void main ( String argvs [ ] )  
{  
// creating object to class
GCDDiff2 object1 = new GCDDiff2 ( ) ;  
ArrayList < Integer > arrList1 = new ArrayList < Integer > ( ) ;  
arrList1 . add ( 4 ) ;  
arrList1 . add ( 6 ) ;  
arrList1 . add ( 8 ) ;  
int size = arrList1 . size ( ) ;  
int ans = object1 . find_GCDs_Sub_seq ( arrList1 ) ;  
  
System . out . println( " For the input array: " ) ;  
for ( int i1 = 0 ; i1 < size ; i1++ )  
{  
System . out . print ( arrList1 . get ( i1 ) + " " ) ;  
}  
System . out . println ( ) ;  
System . out . println ( " The total number of unique GCDs is: " + ans ) ;  
System . out . println ( ) ;  
ArrayList < Integer > arrList2 = new ArrayList < Integer > ( ) ;  
arrList2 . add ( 3 ) ;  
arrList2 . add ( 6 ) ;  
arrList2 . add ( 9 ) ;  
size = arrList2 . size ( ) ;  
ans = object1 . find_GCDs_Sub_seq ( arrList2 ) ;  
System . out . println ( " For the input array: " ) ;  
for( int i1 = 0 ; i1 < size ; i1++ )  
{  
System . out . print ( arrList2 . get ( i1 ) + " " ) ;  
}  
System . out . println ( ) ;  
System . out . println ( " The total number of unique GCDs is: " + ans ) ;  
}  
}  

Output

GCD of Different SubSequences in Java

Related Topics

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

BigDecimal toString() in Java

BigDecimal is a Java class that is a part of the java.math package and the java.base module. It implements the ComparableBigDecimal> interface and extends the Number class. The BigDecimal class...

3 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

How to Return Value from Lambda Expression Java?

What is Lambda Expression in Java? In Java 8, Lambda Expressions were introduced.A lambda expression is a brief section of code that accepts input and outputs a value. Similar to methods,...

4 minutes read.

Java While Keyword

Depending on a specified Boolean condition, a while loop in Java allows code to be executed repeatedly. The while loop can be viewed as an iterative version of the if...

3 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Java Code Coverage Tools

Code coverage testing is a crucial metric that gauges how thoroughly the program's source code has been tested. The market is flooded with Code Coverage Tools, making it difficult to...

7 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

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.

Example of Static import in Java

Static keyword Java's static keyword is mainly used to control memory. Variables, methods, blocks, and nested classes are compatible with the static keyword. Instead of an instance, the static keyword is...

3 minutes read.

Java Garbage Collection Interview Questions

One of the key areas of Java is garbage collection. Garbage collection enables apps to manage memory automatically. Interviewers frequently ask inquiries about garbage collection. Q1: What is the purpose of...

6 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.