Code war . The fusc function -- Part 2

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值