"""
Project Euler problem 2 in cpmpy.

http://projecteuler.net/index.php?section=problems&id=2
'''
Each new term in the Fibonacci sequence is generated by adding the 
previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

Find the sum of all the even-valued terms in the sequence which do not 
exceed four million.
'''

As for euler1.py, using CP for this is overkill.
See http://hakank.org/python/euler.py for better approaches...


Model created by Hakan Kjellerstrand, hakank@hakank.com
See also my CPMpy page: http://www.hakank.org/cpmpy/

"""
from cpmpy import *
import numpy as np
from cpmpy_hakank import *

def euler2():

  n = 35
  f = intvar(0,10000000,shape=n+1,name="f")
  x = boolvar(shape=n+1,name="x")
  res = intvar(0,100000000,name="res")
  
  model = Model([res == sum([x[i]*f[i] for i in range(1,n+1)]),
                 f[0] == 0,
                 f[1] == 1,
                 f[2] == 1,
                 x[0] == 0,
                 [f[i] == f[i-1]+f[i-2] for i in range(3,n+1)],

                 # only even valued < 4000000
                 [((f[i] % 2 == 0) & (f[i] < 4000000)) == (x[i] == 1) for i in range(1,n+1) ]
                 ])

  ss = CPM_ortools(model)
  if ss.solve():
    # print("f:", f.value())
    # print("x:", x.value())
    print("even f and < 4000000:", [f[i].value() for i in range(1,n+1) if x[i].value()==1])    
    print("res:", res.value())

    print()
                

euler2()
