This Java program is designed to solve a specific problem in number theory and sequence analysis. Given a list of integers and a number 'k', the task is to find a subsequence of the list that has the maximum greatest common divisor (GCD) and contains at least 'k' numbers. The program uses a combination of sorting, divisor calculation, and sequence filtering to achieve this.
CodeRankGPT is a tool powered by GPT-4 that quietly assists you during your coding interview, providing the solutions you need.
In real-time and absolutely undetectable 🥷
The solution works by first sorting the input list of numbers. Then, it calculates the divisors for each number in the list. The maximum GCD is determined by checking the divisors from highest to lowest until it finds one that has at least 'k' occurrences. Finally, it filters the original list to include only numbers that are divisible by the maximum GCD. The key algorithm used here is the divisor calculation, which is done by iterating from 1 to the square root of the number and checking if the number is divisible by the iterator. If it is, both the iterator and the result of the division are counted as divisors.
import java.util.ArrayList;
import java.util.List;
public class GCDSubSequence {
static List findMaxGCD(List numbers, int k) {
Object[] original = numbers.toArray();
numbers.sort(Integer::compareTo);
int high = numbers.get(numbers.size() - 1);
int[] divisors = getDivisors(numbers, high + 1);
int maxGcd = hetMaxGcd(divisors, high, k);
return numbersDivisibleBy(original, maxGcd);
}
private static int hetMaxGcd(int[] divisors, int high, int k) {
int maxGcd = 0;
for (maxGcd = high; maxGcd >= 1; maxGcd--) {
if (divisors[maxGcd] >= k) {
break;
}
}
return maxGcd;
}
private static int[] getDivisors(List numbers, int length) {
int[] divisors = new int[length];
for (Integer integer : numbers) {
for (int j = 1; j * j <= integer; j++) {
if (integer % j == 0) {
divisors[j]++;
if (j != integer / j) {
divisors[integer / j]++;
}
}
}
}
return divisors;
}
private static List numbersDivisibleBy(Object[] numbers, int gcd) {
List result = new ArrayList<>();
for (Object number : numbers) {
if ((int) number % gcd == 0) {
result.add((int) number);
}
}
return result;
}
public static List findSubsequence(List numbers, int k) {
return findMaxGCD(numbers, k);
}
static public void main (String[] args) {
List arr = new ArrayList<>();
arr.add(5);
arr.add(4);
arr.add(15);
arr.add(20);
arr.add(1);
int k = 3;
System.out.println(findSubsequence(arr, k));
}
}
If you have a HackerRank Certification test or a coding interview coming up, you can use CodeRankGPT to your advantage. It will assist you during your test and help ensure you get the certification or the job.
AI is here now, and other candidates might be using it to get ahead and win the job. 🧐
The form has been successfully submitted.