4kyu Sums of Perfect Squares
生活随笔
收集整理的這篇文章主要介紹了
4kyu Sums of Perfect Squares
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
4kyu Sums of Perfect Squares
題目背景:
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.
Examples:
sum_of_squares(17) = 2 17 = 16 + 1 (4 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.題目分析:
真心感覺Codewars里面很喜歡出數學題,這道題感覺已經不是程序的思路,就是純粹的數學問題,依據Lagrange’s four-square 理論,任意一個正整數都可以被拆解為4個或4個以下的完美平方數之和,同時如果n = 4^k * (8 * m + 7),那么它決不可能是3個完美正整數之和,所以就很好分析了,對于一個完美平方數或者兩個完美平方數可以直接暴力判別,只需要處理好三個或四個完美平方數之和的判斷即可。
最終AC的代碼:
#include <cmath> int sum_of_squares(int n) {int j = std::sqrt(n);if ( j * j == n ) return 1;for ( int i = 1; i * i <= n; i++ ) {int j = std::sqrt(n - i * i);if ( j * j == (n - i * i) ) return 2;}// based on Lagrange's four-square theorem, any positive integer can be written as the sum of four or fewer perfect squares.// and if n = 4^k * (8 * m + 7), it can't be 3 squares'sumwhile ( n % 4 == 0 ) n /= 4;if ( n % 8 == 7 ) return 4;return 3; }總結
以上是生活随笔為你收集整理的4kyu Sums of Perfect Squares的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 5kyu Square sums (si
- 下一篇: 4kyu Twice linear