Perimeter of squares in a rectangle (5kyu)

Perimeter of squares in a rectangle (5kyu)

Description

The drawing shows 6 squares the sides of which have a length of 1, 1, 2, 3, 5, 8. It’s easy to see that the sum of the perimeters of these squares is :4 * (1 + 1 + 2 + 3 + 5 + 8) = 4 * 20 = 80

Could you give the sum of the perimeters of all the squares in a rectangle when there are n + 1 squares disposed in the same manner as in the drawing:

Squares in a rectangle

Hint:

See Fibonacci sequence

Ref:

http://oeis.org/A000045

The function perimeter has for parameter n where n + 1 is the number of squares (they are numbered from 0 to n) and returns the total perimeter of all the squares.

perimeter(5)  should return 80
perimeter(7)  should return 216

Solution

It can be easily told that the edge of the inner rectangles grows as Fibonacci sequence, which means the length of next edge should be equal to the sum of previous 2. That is:

F(N) = F(N-1) + F(N)

Moreover, to avoid doing repeating calculations, we can store the F(N) we got for referring next time.

fn Fibonacci(n: u64, mut v: &mut Vec<u64>) -> u64 {
    let i = n as usize;
    if *&v[i] != 0 { //has been calculated earlier
        v[i]
    } else { // first time encounter
        v[i] = Fibonacci(n - 1, &mut v) + Fibonacci(n - 2, &mut v);
        v[i]
    }
}

fn perimeter(n: u64) -> u64 {
    let mut v: Vec<u64> = vec![1, 1, 2];
    v.resize(10000, 0);
    v[n as usize] = Fibonacci(n, &mut v);
    4 * v.iter().sum::<u64>()// get perimeter
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值