使用 C++ 检查一个数是否可以表示为两个三角数之和
在本节中,我们将了解是否可以将一个数字表示为两个三角形数字之和。三角形数字如下所示:

从示例中,我们可以看到 1、3、6、10 是一些三角形数字。我们需要将数字 N(例如 16)表示为两个三角形数字(6、10)之和。
方法非常简单。我们必须获取所有小于 N 的三角形数字。从这些值中形成一个集合。现在,我们必须从集合中取一个数字 X,并检查 N – X 是否存在于集合中,然后 X 可以表示为两个三角形数字之和。
示例
#include <iostream>
#include <set>
using namespace std;
bool isSumTriangularNum(int n) {
set<int> s;
int i = 1;
while (1) { //find and store all triangular numbers below n, and store into set
int x = i * (i + 1) / 2;
if (x >= n)
break;
s.insert(x);
i++;
}
for (auto x : s)
if (s.find(n - x) != s.end())
return true;
return false;
}
int main() {
int num = 16;
if(isSumTriangularNum(num)){
cout << "Can be represented";
}else{
cout << "Cannot be represented";
}
}输出
Can be represented
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP