
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Check if a number can be represented as a sum of 2 triangular numbers in C++
In this section, we will see if we can express one number as the sum of two triangular numbers or not. The triangular numbers are like below −
From the example, we can see that 1, 3, 6, 10 are some triangular numbers. We need to express a number N (say 16) as sum of two triangular numbers (6, 10).
The approach is very simple. We have to get all triangular numbers less than N. Form a set from these values. Now we have to take a number say X from the set, and check whether N – X is present in the set, then X can be represented as sum of two triangular numbers.
Example
#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"; } }
Output
Can be represented
- Related Articles
- Check if a number can be represented as sum of non zero powers of 2 in C++
- Check if a number can be expressed as a sum of consecutive numbers in C++
- Check if a number can be expressed as sum two abundant numbers in C++
- Check if a prime number can be expressed as sum of two Prime Numbers in Python
- Check if N can be represented as sum of integers chosen from set {A, B} in Python
- Check if a number can be expressed as 2^x + 2^y in C++
- Check if a number can be written as sum of three consecutive integers in C++
- Count numbers which can be represented as sum of same parity primes in C++
- C++ Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- Java Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
- Swift program to check whether a number can be expressed as sum of two prime numbers
- Program to check a number can be written as a sum of distinct factorial numbers or not in Python
- Check if a number can be expressed as a^b in C++
- Check if a number can be expressed as a^b in Python
- Check if a number can be expressed as power in C++

Advertisements