Project Euler # 45: How is my logic wrong?

From Project Euler, issue 45:

Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

Triangle T_(n)=n(n+1)/2 1, 3, 6, 10, 15, ...

Pentagonal P_(n)=n(3n−1)/2 1, 5, 12, 22, 35, ...

Hexagonal H_(n)=n(2n−1) 1, 6, 15, 28, 45, ...

It can be verified that T_(285) = P_(165) = H_(143) = 40755.

Find the next triangle number that is also pentagonal and hexagonal.

[ http://projecteuler.net/problem=45 ]

Now, to solve them, I took three variables and equated the equations to A.

n(n + 1)/2 = a(3a - 1)/2 = b(2b - 1) = A

A = number at which the three-element function coincides for the values ​​n, a, b

The resulting we get 3 equations with n and A. Solving with a quartite formula, we get 3 equations.

 (-1 + sqrt(1 + 8*A ) )/2
 ( 1 + sqrt(1 + 24*A) )/6
 ( 1 + sqrt(1 + 8*A ) )/4

So my logic is to check the values ​​of A for which the three equations give a natural + ve value. While it works correctly for number 40755 , but cannot find the following up to 10 million.

(Edit): Here is my python code

from math import *

i=10000000
while(1):
    i = i + 1
    if(((-1+sqrt(1+8*i))/2).is_integer()):
        if(((1+sqrt(1+24*i))/6).is_integer()):
            if(((1+sqrt(1+8*i))/4).is_integer()):
                print i
                break

How is my logic wrong? (Apologies for a small part of the math. :))

+5
source share
3

, ( ). , i . .

ypercube.

0

, :

  • heapq.merge ( )

:

import heapq

def hexagonals():
    "Simplified generation of hexagonals"
    n= 1
    dn= 5
    while 1:
        yield n
        n+= dn
        dn+= 4

def pentagonals():
    n= 1
    dn= 4
    while 1:
        yield n
        n+= dn
        dn+= 3

def main():
    last_n= 0
    for n in heapq.merge(hexagonals(), pentagonals()):
        if n == last_n:
            print n
        last_n= n

main()

1, 40755, , , , - 14- . , , .

"" , main ( , , ):

def main():
    hexagonal= hexagonals()
    pentagonal= pentagonals()
    h= next(hexagonal)
    p= next(pentagonal)
    while 1:
        while p < h:
            p= next(pentagonal)
        if p == h:
            print p
        h= next(hexagonal)

, .

+3

The simplest way to implement this is to create 3 generators for each sequence and route them to

heapq.merge

and then, if you find 3 identical keyboards, you get a solution The easiest way to find this is usnig

itertools.groupby

0
source

All Articles