Home > Enterprise >  Run recursion to divide number into largest possible parts until it reaches smallest whole value
Run recursion to divide number into largest possible parts until it reaches smallest whole value

Time:04-30

I need to take a number as input, and continuously run recursion of my function until the number is the smallest prime number the original value can be divided by. I want to divide the value by the smallest value that will return a whole number so that I get the fewest but largest returned numbers.

Example below:

616 / 2 -> 308

308 / 2 -> 154

154 / 2 -> 77

77 / 2 -> ! 38.5

77 / 3 -> ! 25.6

77 / 4 .....

77 / 11 -> 11

The answer is 11 since its the largest whole prime number

My current recursion code:

The methods checkPrime and isWhole are booleans. Check prime returns true if the input value is a prime number, and isWhole returns true is plank length / the value is a whole number.

public static int task(int plankLength,int value) {
            if (checkPrime(value) && isWhole(plankLength,value)) {
                int holdNum = plankLength/value;
                value  ;
                return task(holdNum,value);
            } else {
                value  ;
                return task(plankLength, value);
            }
    }

I get stack overflow issues due to infinite recursion, any ideas on how I can increase the divide number, and if the number has no possible dividends left it will just return that number as "plankLength"

CodePudding user response:

Each branch of your if calls task, so your recursion never terminates; there is no "divide number" that will solve that issue.

CodePudding user response:

Not sure I quite understood your assignment but by the example you proposed I arrived to this solution using a while loop.

public static int task(int num) {

    int div = 2;
    while ( !isPrime(num)) {
        if(isWhole(num,div))
            num = num / div;
        else
            div  ;
    }

    return num;
}
  • Related