Recursion and While Loops in Java - java

I'm writing a recursive program:
public static List<Integer> method(int n)
to determine whether a positive number n is the total of cubes that are positive (> 0). Example: given n = 1944 (12^3 + 6^3), the program would return the list [12, 6] in descending order. If n is not the total of cubes the program should return an empty list.
The program should return the values that start with the highest possible value for the first element, and then follow the same rule for the rest of the elements. For example, when n = 1072, the program would return [10, 4, 2] instead of [9, 7].
The method where the recursion should occur:
private static boolean method(int n, int c, LinkedList<Integer> seen)
where c is the highest number that is still allowed to be used and soFar is the list of numbers that have already been seen.
My code covers the base cases and the recursion, but I'm having issues with the loop continuing. With the input, n = 1944 my program is returning the list [12] instead of [12, 6].
public static List<Integer> method(int n)
{
LinkedList<Integer> result = new LinkedList<Integer>();
int c = (int) Math.cbrt(n);
result.add(c);
method(n, c, result);
return result;
}
private static boolean method(int n, int c, LinkedList<Integer> seen)
{
LinkedList<Integer> result = new LinkedList<Integer>();
boolean b = false;
if (n == 0)
{
return true;
}
else if (c == 0)
{
return false;
}
else
{
int sum = 0;
for (int i : seen)
{
sum += i*i*i;
}
while (b = false)
{
c = (int) Math.cbrt(n - sum);
seen.add(c);
method(n, c, seen);
if (sum == n)
{
result = seen;
return true;
}
else
{
return false;
}
}
}
return false;
}

Let's see your while loop:
LinkedList<Integer> result = new LinkedList<Integer>();
boolean b = false;
// Some code omitted here.
while (b = false)
{
c = (int) Math.cbrt(n - sum);
seen.add(c);
method(n, c, seen);
if (sum == n)
{
result = seen;
return true;
}
else
{
return false;
}
}
First, with a while loop that always has false as the condition for looping, it doesn't do anything at all.
Anyway, even if we pretend the loop runs, whatever is the branch took by the if, a return will be reached. So, your while loop doesn't loop at all even if its condition was changed to always be true. Further, the only value ever assigned for the b variable is false, and it isn't used for anything at all.
Also, the result list in the second method is always empty. And, since the result = seen; instruction is just right before the return, it is an innocuous instruction which renders the result simply being useless.
Also, look at the method(n, c, seen); call. It don't do anything with its return value! So, even if it eventually returns true, you still proceeds, which would then generate false as a result.
Also, whenever you add a value to seen, it will never be removed. Since the seen is always the very same list in every of the recursive method calls, once a bad number is added there, it will never be removed to make the way for something else.
With this, I must conclude that your algorithm is so broken that it must be rewritten from scratch.
Also, although your question isn't very clear, I presume that the numbers found must all be different. Otherwise, one could make 2 = 13 + 13 and every number larger than one could be represented by the sum of a lot of cubed ones (i.e. n = 13 + 13 + 13 + ...).
The algorithm is this:
The first step is to have a for counting i down from cbrt(n) to 1 trying to form cubes.
Then, subtract the cube from n and recursively try to find a cube sum for the resulting number.
Add a parameter to avoid repeating numbers, which is one smaller than the last number used.
When a cube is formed, return the number that formed it. In the outer calls, add the result to the list of non-empty inner recursive call.
If an inner recursive call gives an empty list as a result, then the current iteration of the for produced a bad number and we should try the next one (if we have a next one).
If the for ends without a cube forming, return an empty list.
Here is the code:
import java.util.LinkedList;
import java.util.List;
public class Main {
public static List<Integer> findCubeSum(int n) {
return findCubeSum(n, n);
}
public static List<Integer> findCubeSum(int n, int max) {
if (n <= 0) return List.of();
int c = (int) Math.cbrt(n);
for (int i = Math.min(c, max); i > 0; i--) {
int x = i * i * i;
if (x == n) {
List<Integer> result = new LinkedList<>();
result.add(i);
return result;
}
List<Integer> result = findCubeSum(n - x, i - 1);
if (result.isEmpty()) continue;
result.add(0, i);
return result;
}
return List.of();
}
public static void main(String[] args) {
System.out.println(findCubeSum(8)); // [2]
System.out.println(findCubeSum(64)); // [4]
System.out.println(findCubeSum(1000)); // [10]
System.out.println(findCubeSum(1072)); // [10, 4, 2]
System.out.println(findCubeSum(1944)); // [12, 6]
System.out.println(findCubeSum(4)); // []
System.out.println(findCubeSum(0)); // []
System.out.println(findCubeSum(-1)); // []
System.out.println(findCubeSum(10)); // []
}
}
See it running at ideone.

The code as posted has many issues. However your question is about public static List<Integer> method(int n):
public static List<Integer> method(int n) {
LinkedList<Integer> seen = new LinkedList<>();
method(n, 0, seen);
return seen;
}
Consider changing
private static boolean method(int n, int c, LinkedList<Integer> seen)
To
private static boolean method(int n, LinkedList<Integer> seen)
because you recalculate the value of c by c = (int) Math.cbrt(n);

Related

How to get my function to be recursive? (Java)

I'm having to make a recursive function that will receive a stack of "int" and output the sum of the squares of the elements in the stack.
Here is what I have
public int sum_sqr_rec(Stack<Integer> stk){
int sum = 0;
for (int i=0; i<stk.size(); i++){
sum += (stk.get(i) * stk.get(i));
}
return sum;
}
The most important thing you need to determine for a recursive function is when to terminate it.
The second important thing to consider is what to return when you terminate it. When you start adding numbers, you start with sum = 0. From a recursive function, which is supposed to calculate the sum of numbers, the same value (i.e. 0) can be returned when you terminate it. Similarly, from a recursive function, which is supposed to return the product of numbers, you can return 1 on termination.
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
System.out.println(sum_sqr_rec(stack));
}
static int sum_sqr_rec(Stack<Integer> stk) {
if (stk.isEmpty()) {
return 0;
}
int n = stk.pop();
return n * n + sum_sqr_rec(stk);
}
}
Output:
54
You can use recursion like this:
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.add(2);
stack.add(2);
stack.add(4);
stack.add(5);
System.out.println(sum_sqr_rec(stack));
}
public static int sum_sqr_rec(Stack<Integer> stack) {
if (stack.isEmpty())
return 0;
return stack.peek() * stack.pop() + sum_sqr_rec(stack);
}
Note that I use Deque interface rather than Stack class directly (documentation says it should be used in preference to the Stack class).
public int recursive(Deque<Integer> stk){
if (stk.Empty()){
return 0;
}
return Math.pow(stack.pop(), 2) + recursive(stk);
}
Lots of ways to do this. But if you don't want to destroy the stack you can do it this way. The stack is restored during the return process.
n is popped. This depletes the stack of numbers and keeps n in the local call stack for later use.
The square of the element is saved on the call stack of the method in k
r is initialized for the final tally.
Once the stack is empty, simply push n back on stk and return the sums of the saved squares.
static int sum_sqr_rec(Stack<Integer> stk) {
int n = stk.pop();
int k = n*n;
int r = 0;
if (!stk.isEmpty()) {
r = sum_sqr_rec(stk);
}
stk.push(n);
return r + k;
}
Using this call sequence of statements.
System.out.println(stack);
System.out.println(sum_sqr_rec(stack));
System.out.println(stack);
Results in the following
[2, 3, 4, 5]
54
[2, 3, 4, 5]

Filter odd numbers recursively

How would you solve the following task:
Write a recursive method which gets passed an array, filters all odd numbers and store them into an array. The returned array has to be sorted by each elements order.
You are not allowed to use any provided methods by java classes like Arrays.sort, Lists, etc. Furthermore loops are disallowed and generic well known sort algorithm applied to the result as well.
The part of filtering is easy, but I don't know how to put each element at its right place. At the moment my method only returns an unsorted array with all odd numbers.
public static int[] filterOdd(int[] m){
return filterOdd(m, 0, 0);
}
private static int[] filterOdd(int[] m, int idx, int idxToPlace){
if(idx <= m.length -1){
if(m[idx] % 2 == 0){
return filterOdd(m, idx + 1, idxToPlace);
}else{
int[] buffer = filterOdd(m, idx + 1, idxToPlace + 1);
buffer[idxToPlace] = m[idx];
return buffer;
}
}else{
return new int[numberOfOddIntegers(m)];
}
}
Is there any way to insert the odd number at its right place recursively?
At the place where you do buffer[idxToPlace] = m[idx]; you have to call another method that will return the sorted array with the current processing number added to it.
That new method can be recursive too: you know at that moment that the array you have in your hands is ordered. You just recursively traverse (for example from the end to the begin) and from the moment your element fits in (e.g. is smaller than the previous element) you can insert it and return the sorted array. If there is only 1 element (base case) you can just return it.
That way, at the end of your algorithm, the list will be sorted.
I'm not allowed to use System.arraycopy
This means that you need to figure out how many odd numbers you are going to have, in order to size your result properly:
public static int[] filterOdd(int[] m){
int[] res = new int[countOdd(m, 0)];
filterOdd(m, 0, 0, res);
return res;
}
private static int countOdd(int[] m, int i) {
if (i == m.length) {
return 0;
}
int isOdd = m[i] % 2 != 0 ? 1 : 0;
return isOdd + countOdd(m, i+1);
}
private static void filterOdd(int[] m, int src, int dest, int[] res){
if(src == m.length) {
return;
}
if (m[src] % 2 != 0) {
res[dest++] = m[src];
}
filterOdd(m, src+1, dest, res);
}

Randomizing set of duplicate arrays in Java without repeating elements

In my problem I have few arrays with numbers 1 - 3,
[1,2,3], [1,2,3]
I combined the arrays into one full array,
[1,2,3, 1,2,3]
I need to randomize the array each run, so that no element repeats.
For example, this would work
[1, 2, 1, 3, 2, 3]
but this would not.
[1,2,2,3,1,3]
I chose 1,2,3 to simplify it, but my arrays would consist of the numbers 1 - 6. The idea remains the same though. Is there an algorithm or easy method to accomplish this?
This is a heuristic solution for random shuffling not allowing consecutive duplicates. It applies to lists, but it's easy to transfer it to arrays as it does only swapping and no shift operations are required. It seems to work in the majority of cases for lists consisting of millions of elements and various density factors, but always keep in mind that heuristic algorithms may never find a solution. It uses logic from genetic algorithms, with the exception that this version utilizes one individual and selective mutation only (it's easy to convert it to a real genetic algorithm though), but it's simple and works as follows:
If a duplicate is found, try swapping it with a random element after it; if not possible, try swapping it with an element prior to it (or vice versa). The key point here is the random position for exchanging elements, so as to keep a better uniform distribution on random output.
This question has been asked in alternative forms, but I couldn't find an acceptable solution yet. Unfortunately, as most of the proposed answers (except for the "greedy" extensive re-shuffling till we get a match or computing every combination), this solution does not provide a perfect uniform distribution, but seems to minimize some patterns, :( still not possible to remove every pattern, as you see below. Try it and post any comments for potential improvements.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
//Heuristic Non-Consecutive Duplicate (NCD) Shuffler
public class NCDShuffler {
private static Random random = new Random();
//private static int swaps = 0;
public static <T> void shuffle (List<T> list) {
if (list == null || list.size() <= 1) return;
int MAX_RETRIES = 10; //it's heuristic
boolean found;
int retries = 1;
do {
Collections.shuffle(list);
found = true;
for (int i = 0; i < list.size() - 1; i++) {
T cur = list.get(i);
T next = list.get(i + 1);
if (cur.equals(next)) {
//choose between front and back with some probability based on the size of sublists
int r = random.nextInt(list.size());
if ( i < r) {
if (!swapFront(i + 1, next, list, true)) {
found = false;
break;
}
} else {
if (!swapBack(i + 1, next, list, true)) {
found = false;
break;
}
}
}
}
retries++;
} while (retries <= MAX_RETRIES && !found);
}
//try to swap it with an element in a random position after it
private static <T> boolean swapFront(int index, T t, List<T> list, boolean first) {
if (index == list.size() - 1) return first ? swapBack(index, t, list, false) : false;
int n = list.size() - index - 1;
int r = random.nextInt(n) + index + 1;
int counter = 0;
while (counter < n) {
T t2 = list.get(r);
if (!t.equals(t2)) {
Collections.swap(list, index, r);
//swaps++;
return true;
}
r++;
if (r == list.size()) r = index + 1;
counter++;
}
//can't move it front, try back
return first ? swapBack(index, t, list, false) : false;
}
//try to swap it with an element in a random "previous" position
private static <T> boolean swapBack(int index, T t, List<T> list, boolean first) {
if (index <= 1) return first ? swapFront(index, t, list, false) : false;
int n = index - 1;
int r = random.nextInt(n);
int counter = 0;
while (counter < n) {
T t2 = list.get(r);
if (!t.equals(t2) && !hasEqualNeighbours(r, t, list)) {
Collections.swap(list, index, r);
//swaps++;
return true;
}
r++;
if (r == index) r = 0;
counter++;
}
return first ? swapFront(index, t, list, false) : false;
}
//check if an element t can fit in position i
public static <T> boolean hasEqualNeighbours(int i, T t, List<T> list) {
if (list.size() == 1)
return false;
else if (i == 0) {
if (t.equals(list.get(i + 1)))
return true;
return false;
} else {
if (t.equals(list.get(i - 1)) || (t.equals(list.get(i + 1))))
return true;
return false;
}
}
//check if shuffled with no consecutive duplicates
public static <T> boolean isShuffledOK(List<T> list) {
for (int i = 1; i < list.size(); i++) {
if (list.get(i).equals(list.get(i - 1)))
return false;
}
return true;
}
//count consecutive duplicates, the smaller the better; We need ZERO
public static <T> int getFitness(List<T> list) {
int sum = 0;
for (int i = 1; i < list.size(); i++) {
if (list.get(i).equals(list.get(i - 1)))
sum++;
}
return sum;
}
//let's test it
public static void main (String args[]) {
HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
//initialise a list
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(1);
list.add(2);
list.add(3);
/*for (int i = 0; i<100000; i++) {
list.add(random.nextInt(10));
}*/
//Try to put each output in the frequency Map
//then check if it's a uniform distribution
Integer hash;
for (int i = 0; i < 10000; i++) {
//shuffle it
shuffle(list);
hash = hash(list);
if (freq.containsKey(hash)) {
freq.put(hash, freq.get(hash) + 1);
} else {
freq.put(hash, 1);
}
}
System.out.println("Unique Outputs: " + freq.size());
System.out.println("EntrySet: " + freq.entrySet());
//System.out.println("Swaps: " + swaps);
//for the last shuffle
System.out.println("Shuffled OK: " + isShuffledOK(list));
System.out.println("Consecutive Duplicates: " + getFitness(list));
}
//test hash
public static int hash (List<Integer> list) {
int h = 0;
for (int i = 0; (i < list.size() && i < 9); i++) {
h += list.get(i) * (int)Math.pow(10, i); //it's reversed, but OK
}
return h;
}
}
This is a sample output; it's easy to understand the issue with the non-uniform distribution.
Unique Outputs: 6
EntrySet: [1312=1867, 3121=1753, 2131=1877, 1321=1365, 1213=1793, 1231=1345]
Shuffled OK: true
Consecutive Duplicates: 0
You could use Collections.shuffle to randomize the list. Do it in a while loop, until the list passes your constraint.
If the arrays are relatively small, it would not be too hard for you just to combine the two arrays, randomize it then check the numbers, and if there are too same numbers just shift one over or just randomize it again.
There's no pre-written algorithm that I know of (which doesn't mean one doesn't exist), but the problem is easy to understand and the implementation is straightforward.
I will offer two suggestions dependent on if you want to build a valid array or if you want to build an array and then check its validity.
1 - Create some collection (Array, ArrayList, etc) that contains all of the possible values that will be included in your final array. Grab one of those values and add it to the array. Store a copy of that value in a variable. Grab another value from the possible values, check that it's not equal to your previous value, and add it to the array if it's valid.
2 - Create an array that contains the number of values you want. Check that item n != item n+1 for all items except the last one. If you fail one of those checks, either generate a new random value for that location or add or subtract some constant from the value at that location. Once you have checked all of the values in this array, you know you have a valid array. Assuming the first and last values can be the same.
The most optimal solution, I can think of, is to count the number of occurrences of each value, logically creating a "pool" for each distinct value.
You then randomly choose a value from any of the pools that are not the value of the previous selection. The random selection is weighted by pool sizes.
If a pool is more than half the size of all remaining values, then you must choose from that pool, in order to prevent repetition at the end.
This way you can produce result fast without any form of retry or backtracking.
Example (using letters as values to clarify difference from counts):
Input: A, B, C, A, B, C
Action Selected Pools(Count)
A(2) B(2) C(2)
Random from all 3 pools A A(1) B(2) C(2)
Random from B+C pools C A(1) B(2) C(1)
Random from A+B pools (1:2 ratio) A A(0) B(2) C(1)
Must choose B (>half) B A(0) B(1) C(1)
Random from A+C, so C C A(0) B(1) C(0)
Must choose B (>half) B A(0) B(0) C(0)
Result: A, C, A, B, C, B

Find whether 2 arrays are permutations of each other recursively in Java

I need to build a recursive function that returns true if array a is permutation of array b and false otherwise.
public static boolean isPermutation (int [] a, int [] b)
Can add arguments to the function.
Can NOT use local array.
Can NOT use loops.
Can NOT use library functions.
Can NOT change the arrays.
Does anyone have an idea?
This should work for you, it's basically a loop implemented with recursion. This should execute in quadratic time.
public static boolean isPermutation(int[] a, int[] b, boolean[] ataken, boolean[] btaken, int iter, int totalTaken, int aidx, int bidx)
{
if (a.length != b.length) return false;
// totalTaken is a count of the number of matches we've "taken"
if(totalTaken == a.length) return true;
// don't "loop" b
if(bidx >= b.length)
{
return false;
}
// we should loop through a... this will yield a quadratic runtime speed
if(aidx >= a.length)
{
if (iter < a.length)
{
return isPermutation(a, b, ataken, btaken, iter + 1, totalTaken, 0, bidx);
}
// finished our loop, and "totalTaken" wasn't the whole array
return false;
}
// found a match for this b[bidx]
if(a[aidx] == b[bidx] && !ataken[aidx] && !btaken[bidx])
{
ataken[aidx] = true;
btaken[bidx] = true;
return isPermutation(a, b, ataken, btaken, iter, totalTaken + 1, aidx + 1, bidx + 1);
}
// loop through a
return isPermutation(a, b, ataken, btaken, iter, totalTaken, aidx + 1, bidx);
}
You call it with ataken and btaken arrays filled with false, but of the same length as a and b, respectively.
var isPerm = staticClassName.isPermutation(a, b, ataken, btaken, 0, 0, 0, 0);
The idea is the following: it's a permutation if the product of all members in a is equal to the product of all members in b AND the sum of all members in a is equal to the sum of all members in b.
Write a recursive helper function that will allow you to compute these sums and products and compare them.
Complexity: O(n)
Caveat: can overflow if dealing with many large numbers
See the comments for an important point made by John Carpenter

Java Recursion compilation error

I am a fresh student in computer science and currently we study Java recursion. Unfortunately, the academy only explains the following regarding this topic:
What recursion means.
There are 2 types of cases when using a recursive algorithm: base cases and recursive cases and their purpose.
An example of factorial and Fibonacci implementation using recursion.
Now I got the following exercise:
Two integer numbers will be called "strangers" if their greatest common divisor (aka GTC) is ONLY 1". For example, the numbers 8 and 9 are "strangers" because their GTC is 1. However, 8 and 9 are not "strangers" because their GTC is 2.
Please implement a recursive method which receives an array of integers, and returns "true" if every pair numbers in this array are strangers, and "false" otherwise.
Method signature must be as follows:
public boolean checkGCD(int[] values)
For example:
{3, 5, 7, 11} -> method will returns true.
{4, 7, 8, 9} -> method will returns false because 4 and 8 are not strangers.
For assistance, you can use the following method for finding GTC (Euclidean algorithm):
private static int gcd(int n, int m){
if (m==0)
return n;
return gcd(m,n % m);
}
In addition, the method checkGCD(int[] values) should be overloaded...
Loops cannot be used!
The above can be done very easily with a nested loop, but I must use recursion!
I understand that I need to use an overloaded method which gets the array, lo index and hi index.
So this is what I came up in mind:
######
Base case: if there is at least one pair of numbers in the array which are not strangers, method returns false (no need to continue the comparison...).
######
Comparison will be done in the following way: lo index points to the 1st cell -> hi index points to the 2nd cell -> comparing -> hi index is incremented by 1 until it reaches the last cell of the array.
Then, lo index is incremented by 1, and then repeating the above.
So bottom line, I should compare the first cell to all consecutive cells, compare the 2nd to all consecutive cells, the 3rd etc...
########
If all pairs of numbers are strangers, I need something else to stop recursion. Therefore, if all pairs are strangers, it means that lo index and hi index will eventually point to the last cell (cause both lo and hi index has incremented gradually, and they reach the last array cell after all comparisons turned out to be OK i.e strangers).
The following is the overloaded function:
private static boolean checkGCD(int[] values, int lo, int hi)
{
if ( (gcd(values[lo], values[hi]) )!= 1 )
return false;
else if (lo < values.length-1 && hi < values.length-1)
return checkGCD(values, lo, hi+1);
else if (lo < values.length-2 && hi == values.length-1)
return checkGCD (values, lo+1, lo+2);
if (lo == values.length-1 && hi == values.length-1)
return true;
} -> Compiler says "missing return statement"**
The following is the method the exercise requires to have, and it basically just calls the overloaded method which does everything recursively.
public static boolean checkGCD(int[] values)
{
return checkGCD(values, 0, 1);
}
When I try to compile, I get "missing return statement" which points to the close bracket in the overloaded function
But I do use "return" in the overloaded function.
Please clarify how to fix. I am sure after compilation error, the above overloaded function is still not OK.
You get the compiler error because, if every if fails, the method does not return anything. The solution is add the appropriate return statement when the final if fails.
Not to give the answer away, but here's a strong hint: the base case is an array with two elements. All larger arrays are recursive cases.
There's a general pattern for going through a list with a recursion (pseudocode):
Result f(List f) {
if(f is an empty list) {
return Result for an empty list;
} else {
return (Result for head of list) merged with f(tail of list)
}
}
Since you're using arrays, rather than a type with convenient head() and tail() methods, you could pass in an index to say how much of the array you want to process. When index == array.length you are processing an "empty list".
boolean allMembersPositive(int[] array, int index) {
if(index == array.length) {
return true;
} else {
return (array[index] >=0) && (allMembersPositive(index + 1));
}
}
It's a small step to adapt this to consume two array items per recursive call.
I can guarantee you that when you understand recursion clearly you are going to level up your programming skills.
I recommend reading these URLs:
http://howtoprogramwithjava.com/java-recursion/
http://danzig.jct.ac.il/java_class/recursion.html
Now, lets move back to your questions. I think that is one possible way to implement it:
public class Test {
public static void main(String[] arguments) {
int[] strangers = { 3, 5, 7, 11 };
int[] acquaintances = { 4, 7, 8, 9};
boolean verifyStrangers = checkGCD(strangers);
boolean verifyAcquaintances = checkGCD(acquaintances);
System.out.println(verifyStrangers);
System.out.println(verifyAcquaintances);
}
public static boolean checkGCD(int[] values) {
return checkGCD(values, 0, 1);
}
/*
* I'm really not sure why your professor wants this method signature: "checkGCD(int[] values, int i, int j)"
* I'm coding what I understood from the problem.
*/
private static boolean checkGCD(int[] values, int i, int j) {
boolean result = true;
if (gcd(values[i], values[j]) != 1){
result = false;
}
j++;
if (j < values.length ) {
result = result && checkGCD(values, i, j);
}
return result;
}
private static int gcd(int n, int m) {
if (m == 0)
return n;
return gcd(m, n % m);
}
}
I managed to solve the exercise.
public static int gcd(int n, int m)
{
if (m==0)
return n;
return gcd(m,n % m);
}
private static boolean checkGCD(int[] values, int lo, int hi)
{
// System.out.println("lo is " + lo + " hi is " + hi);
// System.out.println("");
// System.out.println("[lo] is " + values [lo] + " [hi] is " + values[hi]);
// System.out.println("");
if ( (gcd(values[lo], values[hi]) )!= 1 )
return false;
if (lo < values.length-1 && hi < values.length-1)
return checkGCD(values, lo, hi+1);
if (lo < values.length-2 && hi == values.length-1)
return checkGCD(values, lo+1, lo+2);
if (lo == values.length-2 && hi == values.length-1)
return true;
return true;
}
public static boolean checkGCD(int[] values)
{
return checkGCD(values, 0, 1);
}
:-)

Categories

Resources