在C++有没有更好的方法可以做到这一点?检查哪些数字满足条件 [A*B*C = A! + B! + C!]

Is there any better way to do this in C++? Check which numbers satisfy the condition [A*B*C = A! + B! + C!]

本文关键字:满足 数字 条件 方法 更好 有没有 C++ 检查 这一点      更新时间:2023-10-16

这就是我想出的

#include <iostream>
using namespace std;
int serialNumber = 1;

递归会更好吗?

int factorial(int n)
{
int k=1;
for(int i=1;i<=n;++i)
{
k=k*i;
}
return k;
}

如何在单个 for 循环中执行此操作? 或者这是最好的方法?

int main()
{
int a;
int b;
int c;
int fact1;
int fact2;
int fact3;
for (a=1;a < 11;a++)
{
fact1 = factorial(a);
for (b=1;b < 11;b++)
{
fact2 = factorial(b);
for (c=1;c < 11;c++)
{
fact3 = factorial(c);
cout << serialNumber << " : ";
int LHS = fact1 + fact2 + fact3;
if (LHS == a * b * c)
{
cout << "Pass:" <<"    "<< a << " & " << b << " & " << c << endl;
}
else
{
cout << "Fail" <<endl;
}
serialNumber++;
}
c = 1;
}
b = 1;
}
return 0;
}

我被迫在其中添加更多无代码。 感谢您的帮助!

不知道这是否有帮助,但>检查 A,B,C 的最小值

A!+B!+C! = (min(A,B,C)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))

因此,您可以计算最小阶乘,然后重复使用它来计算其他阶乘。 另一方面,您可以仅计算最大阶乘并将其结果存储在数组中,并重用预先计算的值来查找较小数字的阶乘

另一个含义是可以减少最小数量

restfact1 * restfact2 = ((min-1)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))

部分问题是如何在单个循环中完成此操作,这是执行此操作的一种方法。

我不认为这是更好的方法,但有人问了这个问题:

constexpr int bound = 10;
int Factorials[bound + 1];
for (int i = 1; i <= bound; ++i) Factorials[i] = Factorial(i);
for (int i = 0; i < bound * bound * bound; ++i) {
int s = i + 1;
int a = i;
int c = 1 + a % bound;
a /= bound;
int b = 1 + a % bound;
a /= bound;
++a;
cout << s << " : ";
int LHS = Factorials[a] + Factorials[b] + Factorials[c];
if (LHS == a * b * c)
...
}