A triangular number or triangle number counts objects arranged in an equilateral triangle. Their formula is n(n+1)/2.
I want to write a number as the sum of two triangular numbers. ( 24=21+3 ; 48=45+3 )
I have written some code in C++ that does this pretty well for smaller numbers. But as N gets bigger it becomes slower and slower, which makes me think my code is inefficient or downright wrong. So I am asking for suggestions.
I am open to and would appreciate any criticism or ideas you might have. Here's what I came up with.
It generates the number "i" and gives "j" the value of x-i. It tests if both the numbers are triangular (iok, jok) and if they are, it prints them out and ends. If it doesn't find such numbers, it prints "NO".
#include <iostream>
using namespace std;
int main(){
long long x;
cin>>x;
long long j,i;
int iok,jok;
long sum;
long long n;
for(i=1;i<=x;i++){
iok=0;
sum=0;
for (n=1; sum<=i; n++)
{
sum = sum + n;
if (sum==i)
iok=1;
}
j=x-i;
jok=0;
sum=0;
for (n=1; sum<=j; n++)
{
sum = sum + n;
if (sum==j)
jok=1;
}
if(jok && iok){
cout<<i<<" "<<j;
return 0;
}
}
cout<<"NO";
return 0;
}