In the following problem I have to find the number > 40755 which is triangular,pentagonal and hexagonal. The formulas for these type of numbers are given below. As I read every hexagonal number is also triangular so we have to compare pentagonal with hexagonal numbers. This algorithm gives 9 digit number 969480682 for about 20 minutes which is too slow. Any help concerning the speed and corectness will be greatly appreciated.

#include <stdio.h>
int Pentagonal(int n){
	int P = 0;
	P = (3*n*n - n) / 2;
	return P;
}
int Hexagonal(int m){
	int H = 0;
	H = m*(2*m - 1);
	return H;
}
void compare(int P,int H){
	if(P == H)
		{printf("\n%d",H);
		}
}
int main(){
	for(int i = 100; i<100000; i++)
		{
		for(int j = 100; j<100000; j++)
		{
		compare(Pentagonal(i),Hexagonal(j));
		}
		}
	return 0;
}

Edited 5 Years Ago by george61: n/a

Hint: You don't need to calculate hexagonal numbers. You just need to test if a given number is hexagonal. In other words, find out if the equation
x*(2*x - 1) = P(i)
has integer roots.

Comments
here, have some bling

Thanks for the help this method is much faster. Using even double I get that the second number satisfying the condition is 40755(that's right) but for the 3rd number there is some kind of overflow and I get negative result which is impossible.

#include <stdio.h>
#include <math.h>
double Pentagonal(int n){
	double P = 0;
	P = (3*n*n - n) / 2;
	P = -P;
	return P;
}
int Equation(){
	double x1,x2,remainder = 0;
	//where the cycle starts
	int n = 166;
	//variable for the remainder
	int x = 0;
	//quadratic equation quotients
	int a = 2;
	int b = -1;
	double c = 0;
	for(n; n<100000; n++)
		{c = Pentagonal(n);
		double root = sqrt(b*b - 4*a*c);
		x1 = (-b + root)/(2*a);
		x = (-b + root)/(2*a);
		remainder = fmod(x1,x);
		x2 = (-b - root)/(2*a);
		if(remainder == 0)
			{printf("%.4lf",x1);
			printf("\nNumber is %.0lf\n",-c);
		break;}
		}
	return 0;
}
int main(){
	Equation();
	return 0;
}
This article has been dead for over six months. Start a new discussion instead.