Knuth Numbers recursion - Printable Version +- BP Forums (https://bpforums.info) +-- Forum: Programming Discussion (https://bpforums.info/forumdisplay.php?fid=34) +--- Forum: Java (https://bpforums.info/forumdisplay.php?fid=41) +--- Thread: Knuth Numbers recursion (/showthread.php?tid=898) |
Knuth Numbers recursion - Miriam - 04-21-2015 Hello, I recently had a final exam on which my teacher asked to write a method for Knuth numbers recursion. I got a stack overflow on my implementation, and I am new on Java, so I am not sure what happened, it might be that I had the wrong formula for Knuth numbers? I would love some feedback. Here is the question, and my code Knuth numbers are given by the recursive formula Kn+1 = 1 + min (2 * Ka, 3 * Kb) where a is the smallest integer larger than n/2.0 and b is the smallest integer larger than n/3.0. The use of doubles in the denominator is necessary to ensure that integer division is not used. For example, if n is 7, then a equals 4 and b equals 3 and thus K8 = 1 + min (2* K4, 3 * K3). If n is 8, then a equals 5 while b remains 3 and thus K9 = 1 + min (2 * K5, 3 * K3). If n is 9, then a remains 5 while b equals 4 and thus K10 = 1 + min(2 * K5, 3 * K3). Mathematically, “the smallest integer larger than x†is the “ceiling†function. If n is an int, then n / 2 is calculated using integer division, discarding the remainder; but you want the division to give you a double. Thus you need code that looks like this: int a = Math.ceil(n / 2.0); int b = Math.ceil(n / 3.0); Since the equation defining Knuth numbers is a recursive one, we must have a base case; let’s assume that K0 = 1. Create and test a class called KnuthNumbers (in a project also called KnuthNumbers) which includes a static method to compute Knuth numbers. my code: Code: public class KnuthNumbers TEST: Code: public class KnuthNumbersTest RE: Knuth Numbers recursion - brandonio21 - 04-22-2015 Hey Miriam, good to see you here and welcome to BP Forums! So I was looking into your problem, and I was having a lot of difficulty with it, too. That is, until I researched the definition of Knuth numbers. According to WolframAlpha, the Knuth numbers are actually defined as: That is, Kn+1 = 1 + min(2Ka, 3Kb) where: a = floor(n/2) b = floor(n/3) Thus, using floor instead of ceil, we are able to simplify the algorithm to something like this: Code: public class KnuthNumbers As you can see, there are a few things that have changed from your definition. I'll outline them below:
I hope this helped! |