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

更新於:2019年9月27日

129 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.