-
Triangular number
Triangular number is the amount of point that can fill equilateral triangle. For example number 6 is triangular number because all sides of triangle has the same amount of point. The problem for this task is to solve equation T(n) = n * (n + 1) / 2. t(n) is given we are searching n. My code below
Code:
#include <stdbool.h>
bool is_triangular(int t) {
unsigned long long int delta = 1+8*t;
double x=(-1+sqrt(delta))/2.0;
if(floor(x)==x)
return true;
return false;
}
It gives me proer solutions except t==458000245 and for t==453351216. I don't know where is the problem.
-
int is 32 bits long (UINT_MAX = 4294967295)
long long is 64 bits long
double is 53. Try:
Code:
bool is_triangular( unsigned long long t )
{
unsigned long long delta = 1ULL+8ULL*t;
long double x = (-1.0L + sqrtl(delta)) / 2.0L;
return floorl( x ) == x;
}
-
Problem solved