Sums of Perfect Squares (4kyu)

该文描述了一个编程任务,基于拉格朗日四平方定理,要求开发一个算法找出能表示给定正整数n(3<n<10^9)为最小数量完美平方和的长度。对于特定情况,分别处理n等于其平方根的平方、两平方和、不能表示为四个平方的情况,并给出不同时间复杂度限制的测试用例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sums of Perfect Squares (4kyu)

Description

The task is simply stated. Given an integer n (3 < n < 109), find the length of the smallest list of perfect squares which add up to n. Come up with the best algorithm you can; you’ll need it!

Examples:

  • sum_of_squares(17) = 2
    17 = 16 + 1 (16 and 1 are perfect squares).
  • sum_of_squares(15) = 4
    15 = 9 + 4 + 1 + 1. There is no way to represent 15 as the sum of three perfect squares.
  • sum_of_squares(16) = 1
    16 itself is a perfect square.

Time constraints:

5 easy (sample) test cases: n < 20

5 harder test cases: 1000 < n < 15000

5 maximally hard test cases: 5e8 < n < 1e9

1000 random maximally hard test cases: 1e8 < n < 1e9

Solution

The task is based on Lagrange’s four-square theorem, any positive integer can be written as the sum of four or fewer number’s square.

Specially, if n = 4^k * (8 * m + 7), n can not be the sum of 4 squares.

So, there are cases:

  1. n equals to the square of its root as u64, return 1.
  2. Use a loop to find out if n is sum of only 2 squares.
  3. Check if n applys to the equation above, return 4 if yes or 3 else.
fn sum_of_squares(n: u64) -> u64 {
    //case 1
    let num = (n as f64).sqrt() as u64;
    if (num*num) as u64 == n{
        return 1;
    }
    //case 2
    let end = (n as f64).sqrt() as u64;
    for i in 1..=end{
        let left = ((n - i*i) as f64).sqrt() as u64;
        if left*left == (n - i * i) {
            return 2;
        }
    }
    //case 3
    let mut remaining = n;
    while remaining % 4 == 0{
        remaining /= 4;
    }
    if remaining % 8 == 7{
        return 4;
    }
    //case 4
    return 3;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值