0

I'm trying to make a program that calculates Brown numbers, or numbers that can be expressed as n!+1 = m^2 where m is an integer, and running this through creates too big of a number.

Any idea how to fix this? (There is also an abacist style method but it takes exponentially longer)

n = 40320
f = 9
while True:
    x = (n+1)**(.5)
    if isinstance( x, int ):
        break
    else:
        n = n*f
        f = f+1
print(f)
print(n)
print(input(" "))

*n is 8!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Z.B
  • 21
  • 2
  • Unless I am missing something, you never calculate `n!`. `n` and `f` always increase – OneCricketeer Nov 09 '16 at 21:34
  • 8! = 40320, and a factorial is just 9*8*7*6*5*4*3*2*1 so doing 9*8! = 9! – Z.B Nov 09 '16 at 21:39
  • Right... And you are going to hit an overflow error eventually at some point, regardless of any provided "fix". So what is the issue? – OneCricketeer Nov 09 '16 at 21:40
  • I need either some way to circumvent the problem as to continue through a large amount of numbers so I can do these calculations Also I'm trying to figure out why it starts with the overflow error – Z.B Nov 09 '16 at 21:43
  • 1
    [Only three such numbers are known](https://www.wolframalpha.com/input/?i=Brown+numbers). And 9 is much higher than *any* of those values... Python (and most programming languages) are limited by hard integer & floating point size limits of your computer. – OneCricketeer Nov 09 '16 at 21:45
  • The highest one is 7(7!+1= 71^2) , and the program begins at 8!, 40320. I assume by that means that it's a computer hard limit then. – Z.B Nov 09 '16 at 21:49
  • Yeah, your code crashes from an overflow – OneCricketeer Nov 09 '16 at 21:53

1 Answers1

0

Your loop will never end because x will never be of type int:

>>> 4**0.5
2.0
>>> isinstance(4**0.5, int)
False
>>> isinstance(4**0.5, float)
True

May I suggest this alternative:

x = (n+1)**(.5)
x = int(round(x))
if x ** 2 == n + 1:
    break

This should also handle floating point accuracy issues.

EDIT: the above was a simple method for small numbers. To check if a large number is a perfect square there are other methods such as this one: https://stackoverflow.com/a/2489519/2482744

Community
  • 1
  • 1
Alex Hall
  • 34,833
  • 5
  • 57
  • 89