简体   繁体   English

试图通过 python 中的递归来解决 Project Euler(问题 3)中的最大素因子问题

[英]Trying to solve the Biggest Prime Factor problem from Project Euler (Problem 3) through recursion in python

I have been trying to solve Problem #3 in ProjectEuler in python.我一直在尝试解决 python 中 ProjectEuler 中的问题 #3。 I have tried using recursion to get factors of my factors.我尝试使用递归来获取我的因子的因子。 But I keep on running into a recursive limit reached error for some reason.但是由于某种原因,我不断遇到递归限制达到错误。 Can anyone help me out as to why its happening?任何人都可以帮助我了解它为什么会发生吗?

def getPrimeFactors(y):
  AllFactors = [[x, int(y/x)] for x in range(1, (int(math.sqrt(y)+1))) if y%x==0]
  Flattened_AF = [j for i in AllFactors for j in i]
  print(AllFactors)
  print(Flattened_AF)

  if len(Flattened_AF)==2:
    print(Flattened_AF)
    return Flattened_AF
  else:
    PrimeFactors = [x for x in Flattened_AF if len(getPrimeFactors(x))==2]
    print (f'loop in else - {PrimeFactors}')
    print(max(PrimeFactors)

getPrimeFactors(4)

This is the problem as quoted in the website.这是网站上引用的问题

I am sorry if the code readability quality is a bit low but I had been trying to debug for a long time in vain.如果代码可读性质量有点低,我很抱歉,但我尝试调试了很长时间都没有成功。

When you define AllFactors for in input y , you iterate from 1, so the same number y is always contained within AllFactors.当您在输入y中定义 AllFactors 时,您从 1 开始迭代,因此相同的数字y始终包含在 AllFactors 中。 As such, when you call getPrimeFactors on the input, that same input y is passed, so this becomes an infinite loop.因此,当您在输入上调用 getPrimeFactors 时,会传递相同的输入y ,因此这成为一个无限循环。

Iterating from 2 instead of 1 stops the recursion error.从 2 而不是 1 迭代停止递归错误。

Also, just a tip, typically in python variables names begin with a lower case and classes begin with uppercase.此外,只是一个提示,通常在 python 中,变量名称以小写字母开头,类以大写字母开头。 There is more about naming conventions here: https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html .这里有更多关于命名约定的信息: https://visualgit.readthedocs.io/en/latest/pages/naming_convention.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM