@kryptomega,
You don't actually state what your problem is!
You do, however, have a huge amount of repetition and you are comparing floating-point numbers for exact equality, which is always dangerous, due to the finite accuracy with which they can be stored. Although I haven't done that below, the test for a triangle number is equivalent to whether 8n+1 is a square number (as you are clearly intending in your code).
#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
using INT = unsignedlonglong;
//======================================================================
bool isSquare( INT N )
{
INT r = sqrt( 0.5 + N ); // Deliberate use of truncation
return r * r == N;
}
//======================================================================
bool isTriangular( INT N )
{
INT r = 0.5 * sqrt( 1.0 + 8.0 * N ); // Deliberate use of truncation
return r * ( r + 1 ) / 2 == N;
}
//======================================================================
int main()
{
string result[] = { "neither", "square", "triangular", "both" };
for ( INT i = 1; i <= 100; i++ ) cout << i << ": " << result[ isSquare(i) + 2 * isTriangular(i) ] << '\n';
}
#include <iostream>
#include <string>
#include <cmath>
usingnamespace std;
bool isSquare( longlongint N ){
longlongint r = sqrt( 0.01 + N );
return r * r == N;
}
bool isTriangular( longlongint N ){
longlongint r = 0.5 * sqrt( 1.0 + 8.0 * N );
return r * ( r + 1 ) / 2 == N;
}
int main(){
longlongint i;
cin>>i;
string result[3] = { "Neither", "Square", "Triangular", "Both" };
cout <<result[ isSquare(i) + 2 * isTriangular(i) ] << '\n';
}
But turned out with error "too many initializers for ‘std::string [3] {ak std::basic_string<char> [3]}’
@string result[3] = { "Neither", "Square", "Triangular", "Both" };
What's my problem?
Thanks!
P.S.
Sample input and output for your reference:
e.g. 1
Input: 10
Output: Triangular
e.g. 2
Input: 25
Output: Square
e.g. 3
Input: 37
Output: Neither
e.g. 4
Input: 36
Output: Both