[英]Given a number N how many pairs of numbers have square sum less than or equal to N?
Let's define F(N) as the number of pairs of distinct positive integers (A,B) such that A 2 +B 2 ≤N and A<B . 让我们定义F(N),其对不同的正整数(A,B),使得A 2 + B 2≤N和A <B的数。
If N=5 the only possible such pair is (1,2) for N=10 the pairs are two: (1,2) and (1,3) . 如果N = 5,则唯一可能的配对是(1,2) ,而N = 10,则配对是两个: (1,2)和(1,3) 。
Furthermore we have F(13)=3 , F(17)=4 , F(17)=4 , F(20)=5 , F(20)=5 , F(25)=6 , F(100)=31 and so on for every number which is sum of two distinct non-zero squares. 此外,我们有F(13)= 3 , F(17)= 4 , F(17)= 4 , F(20)= 5 , F(20)= 5 , F(25)= 6 , F(100)=每个数字都是31 ,依此类推,这是两个不同的非零平方之和。
So far I have the following solution: 到目前为止,我有以下解决方案:
long long SOLVE(lld n)
{
long long x=sqrt(n),up=0;
long long a=x,b=1;
while(abs(a-(b-1))!=1)
{
while(sqr(a)+sqr(b)<=n )
{
b++;
}
up+=(b-1);
a--;
}
b--;
up+=(b*(b+1))/2;
return up;
}
int main()
{
cout<<number(100);
return 0;
}
Same numbers are not countable, thus (1,1) and (2,2) are invalid tuples. 相同的数字不可计数,因此(1,1)和(2,2)是无效的元组。 Same combination but different order counts only once. 相同的组合但不同的订单仅计算一次。 Thus (1,2) and (2,1) count only as once. 因此(1,2)和(2,1)仅计一次。
But as the range of N is 1, I need a more efficient algorithm or formula to calculate this. 但是,由于N的范围为1,因此我需要一种更有效的算法或公式来进行计算。 Is there any trick to make my code more efficient? 有什么技巧可以使我的代码更高效?
In pseudocode: 用伪代码:
int count=0;
for (smaller=1; ;++smaller)
{
maxlarger = floor(sqrt(N-smaller*smaller));
if (maxlarger <= smaller)
break;
count+=(maxlarger-smaller);
}
return count;
You do not have to calculate the number of B 's: you can simply calculate the largest B for which this is possible, which is immediately the number of tuples for that A : 您不必计算B的数目:您可以简单地计算出可能的最大B数,即立即为该A的元组数:
B max =sqrt(NA 2 ) , and the lower-bound on B is: B min =A+1 . B max = sqrt(NA 2 ) ,并且B的下限是: B min = A + 1 。
Now you can do the following: 现在,您可以执行以下操作:
So this leads us to the following algorithm: 因此,这导致我们得出以下算法:
lld SOLVE(lld n) {
lld aM=sqrt(n);
lld a=1;
lld res = 0;
for(lld a = 1; a < aM; a++) {
int nB = sqrt(n-a*a)-a;
if(nB > 0) {
res += nB;
} else {
break;
}
}
return res;
}
from the moment, no more B values can be found, one can break off the search. 从那一刻起,再也找不到B值,可以中断搜索。
I've written a demo here which seems to work. 我在这里编写了一个似乎可行的演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.