I tried to solve the problem problem No. 276 from Project Euler , but so far failed.
Consider triangles with integers on the sides a, b, and c with ≤ b ≤ c. an integer triangle (a, b, c) is equal to a called primitive if gcd (a, b, c) = 1. How many primitive integer triangles exist with a perimeter not exceeding 10,000,000?
The bottleneck in my code is function GCD. For my sample input, almost 90% of the lead time. I would like to hear tips, comments on how to improve the solution ... My solution is written in C, but it is just simple:
#include <stdio.h>
#include <math.h>
#define sides 3
size_t bi_gcd (size_t a, size_t b);
size_t tri_gcd (size_t a, size_t b, size_t c);
size_t count_primitive_triangles (size_t maximum_perimeter);
int main()
{
printf( "primitive_triangles = %lu \n",
count_primitive_triangles(1000) );
}
size_t bi_gcd (size_t a, size_t b)
{
size_t t;
while(b != 0)
{
t = b;
b = a % b;
a = t;
}
return a;
}
size_t tri_gcd (size_t a, size_t b, size_t c)
{
return bi_gcd(a, bi_gcd(b, c));
}
size_t count_primitive_triangles (size_t max_perimeter)
{
size_t count = 0;
size_t a, b, c;
size_t
a_limit = max_perimeter/sides,
b_limit,
c_limit;
for (a = 1; a <= a_limit; ++a)
{
for (b = a, b_limit = (max_perimeter-a)/2; b <= b_limit; ++b)
{
for (c = b, c_limit = a+b; c < c_limit; ++c)
{
if (tri_gcd(a, b, c) == 1)
++count;
}
}
}
return count;
}
source
share