使用 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