首页 文章资讯内容详情

在C ++中计算其立方和为N(a ^ 3 + b ^ 3 = N)的计数对(a,b)

2026-06-04 1 花语

给我们一个数字N。目标是找到有序的正数对,以使它们的立方之和为N。

我们将通过找到方程a3+b3=N的解来实现这一点。其中a不大于N的立方根,并且b可以计算为(Na3)的立方根。

让我们通过示例来理解。

输入项

N=35

输出结果

Count of pairs of (a,b) where a^3+b^3=N: 2

说明

Pairs will be (2,3) and (3,2). 23+33=8+27=35

输入项

N=100

输出结果

Count of pairs of (a,b) where a^3+b^3=N: 0

说明

No such pairs possible.

以下程序中使用的方法如下

我们取整数N。

函数cubeSum(intn)取n并返回多维数据集之和为n的有序对的计数。

对于成对的初始变量计数为0。

使用for循环遍历查找一个。

从a=1到a<=cbrt(n),它是n的立方根。

将b的立方计算为n-pow(a,3)。

计算b为cbrt(bcube)

如果pow(b,3)==bcube。增量计数为1。

在所有循环结束时,计数将包含此类对的总数。

返回计数结果。

示例

#include <bits/stdc++.h> #include <math.h> using namespace std; int cubeSum(int n){ int count = 0; for (int a = 1; a < cbrt(n); a++){ int bcube=n - (pow(a,3)); int b = cbrt(bcube); if(pow(b,3)==bcube) { count++; } } return count; } int main(){ int N = 35; cout <<"Count of pairs of (a,b) where a^3+b^3=N: "<<cubeSum(N); return 0; }

输出结果

如果我们运行上面的代码,它将生成以下输出-

Count of pairs of (a,b) where a^3+b^3=N: 2