0

I have written a program that generates all possible list of first 32 natural numbers and checks if the sum of the adjacent numbers is a perfect square.

The programs has to iterate over 2.3e25 lists(pretty lot of zeroes). whenever I run the program the python kernel crashes. How do I run this program

My code is

from itertools import permutations
import math 
def check(nums):
    
    for i in range(len(nums) - 1):
      y = nums[i] + nums[i + 1]
      z = y ** 0.5
      #till here found the square root of the sum of the adjacent numbers in list
      if z.is_integer() ==False:
        
      # if there is some two numbers that don't meet condition, function will return False
        return False
      return nums

x = list(permutations(range(1, 33)))

for q in range(len(x)):
    if (check(x[q])):
        print(x[q])
        break

The answer set I am looking for is [1,8,28,21,4,32,17,19,30,6,3,13,12,24,25,11,5,31,18,7,29,20,16,9,27,22,14,2,23,26,10,15].

Kindly help me out

PS Thanks to members who helped me in writing the function earlier My earlier question

Avinash K
  • 43
  • 5

1 Answers1

0

x is way, way too big to be stored as a list. permutation creates a generator, which means it will generate the values on the fly. That allows you to iterate over it without storing all the values.

x = permutations(range(1, 33))

for num in x:
    if (check(num)):
        print(num)
        break

Although this answers your question, your program still won't solve your problem. The problem isn't brute force-able like this.

Loocid
  • 6,112
  • 1
  • 24
  • 42