This Kata is a continuation of Part 1. The
fusc
function is defined recursively as follows:
fusc(0) = 0 fusc(1) = 1 fusc(2n) = fusc(n) fusc(2n + 1) = fusc(n) + fusc(n + 1)
Your job is to produce the code for the
fusc
function. In this kata, your function will be tested with large values ofn
(more than 1000 bits), so you should be concerned about stack overflow and timeouts.NOTE: In JavaScript and PHP, your function will be tested with n up to 52 bits. This will still require a non-naive solution. This will also overflow 32-bit operators, but it will be integer arithmetic.
Hint: Define
F(n, a, b) = a * fusc(n) + b * fusc(n + 1)
and provide a recursive definition ofF
without referencingfusc
.
import java.math.BigInteger; public class Fusc { public static BigInteger fusc(BigInteger n) { return F(n, BigInteger.valueOf(1), BigInteger.valueOf(0)); } private static BigInteger F(BigInteger n, BigInteger a, BigInteger b) { // F(n,1,0) = f(n) // F(0,a,b) = b // F(1,a,b) = a+b // F(2n,a,b) = F(n,a+b,b) // F(2n+1,a,b) = F(n,a,a+b) if (n.compareTo(BigInteger.ZERO) == 0) { return b; } if (n.compareTo(BigInteger.ONE) == 0) { return a.add(b); } if (n.mod(BigInteger.valueOf(2)).compareTo(BigInteger.ZERO) == 0) { return F(n.divide(BigInteger.valueOf(2)), a.add(b), b); } return F(n.divide(BigInteger.valueOf(2)), a, a.add(b)); } }
Code war . The fusc function -- Part 2
最新推荐文章于 2022-07-06 22:41:38 发布