标签:ace out algorithm i++ math.h math namespace int mat
对于一个非负整数n,最少需要几个完全平方数,使其和为n?
输入包含多组数据。对于每组数据:
第一行是n;如果n为-1,表示输入结束。(0 <= n <= 1000000001)
针对每组数据,输出最少需要的完全平方数。
样例输入
3 4 5 -1
样例输出
3 1 2
#include <iostream>
#include <algorithm>
#include<math.h>
#include <queue>
using namespace std;
bool is_sqrt(long long n)
{
int m = sqrt(n);
if (m*m == n)
return true;
else
return false;
}
int solve(long long n)
{
if (is_sqrt(n))
return 1;
while (n % 4 == 0)
n /= 4;
if (n % 8 == 7)
return 4;
for (int i = 0; i*i < n; i++)
{
if (is_sqrt(n - i*i))
return 2;
}
return 3;
}
int main()
{
long long n;
while (cin>>n)
{
if (n == -1)
break;
cout<< solve(n)<<endl;
}
return 0;
}
有其它难的方法我没看懂,太菜了,只看懂这种,那个大神挺牛的
标签:ace out algorithm i++ math.h math namespace int mat
原文地址:http://www.cnblogs.com/xzxj/p/6580736.html