Project Euler Problem 600 Integer sided equiangular hexagons - Solution


Integer sided equiangular hexagons

   

Problem 600

Let H(n) be the number of distinct integer sided equiangular convex hexagons with perimeter not exceeding n.
Hexagons are distinct if and only if they are not congruent.
You are given H(6) = 1, H(12) = 10, H(100) = 31248.
Find H(55106).
p600-equiangular-hexagons.pngEquiangular hexagons with perimeter not exceeding 12


First convert this problem into below equivalent problem:

Find integers: a,b,c
(1) a<=b<=c
(2) 3x-(a+b+c)<=n
(3) x>=(a+b+c)

The 2 problems are equivalent, how?

a) Add 3 small triangles (a,a,a), (b,b,b), (c,c,c) at each corner of the hexagons, to form a large triangle (x,x,x), due to summitry, simple define (1) a<=b<=c

b) As each hexagon has 2 possible x- triangles, in order not to count the same solution twice, always use the one with a smaller x. 
Thus, we have 3x <= c+2(x-b-c)+b+2(x-a-b)+a+2(x-a-c); <=> (3) x>=(a+b+c)

c) Equiangular <=n, thus (a+b+c) + (x-a-b) + (x-a-c) + (x-b-c) <= n; <=> (2) 3x-(a+b+c)<=n

With minimum optimization, implement this in c++ as below.
It returns correct answer in a few hours.
Let me know if you have better approach.


#include<iostream>  
#include<algorithm>
  
using namespace std; 
  
//add 3 small triangles(a,a,a) (b,b,b) (c,c,c) at each corner to form a large triangle (x,x,x)
//each hexagon has 2 possible x-triangles, always use the one with smaller x => (1) x>=(a+b+c)
//the original problem becomes: all int solutions a,b,c,x (2) a<=b<=c, (3) 3x-(a+b+c)<=n
//clockwise the hexagon would be(a,x-a-b,b,x-b-c,c,x-c-a)
int main() 
{ 
    const long long maxn = 55106;
    long long count = 0;
 for (long long x=1;x<= maxn*2/3;x++){  
  for (long long a =1;a<=x/3;a++){
   for (long long b =a;b<=x/2;b++){
    // from (1),(2),(3)
    // c>=b c>=3x-n-(a+b) c<=x-a-b
    long long result = (x-a-b) - max(b,3*x-maxn-a-b) +1;
    if (result>0){
     count += result; 
                }
            }
        }
        if(x%100==0){
   cout<<x<<"\t"<<count<<endl;           
        }
    }  
    return count; 
} 

Comments

Popular posts from this blog

Project Euler Problem 684 Inverse Digit Sum - Solution

Project Euler Problem 686 Powers of Two - Solution

Project Euler Problem 717 Summation of a Modular Formula - Solution