Code war . The fusc function -- Part 2

来源:互联网 发布:snmp网管软件 免费 编辑:程序博客网 时间:2024/06/17 15:03

This Kata is a continuation of Part 1. The fusc function is defined recursively as follows:

fusc(0) = 0fusc(1) = 1fusc(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 of n (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 of F without referencing fusc.


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));    }}

原创粉丝点击