繁体   English   中英

找出所有能整除一个数的数

[英]Finding all numbers that evenly divide a number

所以我正在尝试制作一个程序,当我输入一个数字时,它会给我所有的因素( 12 -> 1,2,3,4,6,12 )。 我最近才开始编程,所以可能有一些非常明显的事情。 但这是我的代码

numbers = [1]
newnum = 1
chosen = int(input("Enter what you want the factors of: "))
def factors(numbers,newnum,chosen): 
    lastnum = numbers[-1]
    if (chosen == lastnum):
        for number in numbers:
            if (number % 1 != 0):
                numbers.remove(number)
                print (numbers)
            else:
                factors(numbers,newnum,chosen)
    else:
        newnum = numbers[-1] + 1
        numbers.append(newnum)
        print (numbers)
        factors(numbers,newnum,chosen)

factors(numbers,newnum,chosen)  

好的,所以我真的不需要解决冗余问题,但是如果您看到会完全阻止程序运行的内容,请指出。 抱歉,我为此打扰了大家,但我不知道还能做什么。

有很多问题:

  • 每个以 1 为模的整数都是零,因为每个整数都可以被 1 整除而没有余数。

  • 您从正在迭代的列表中删除项目,如果您不小心操作,那肯定会给出错误的结果!

  • 您尝试进行递归,但不返回递归调用的结果。 这是可能的,因为你在一个可变列表上操作,但它通常不是很好的风格

  • 您没有任何内联注释来解释该行应该做什么,因此很难就如何改进代码提供任何合理的指导。

如果您想要找到所有因素的代码,请考虑这样的事情:

chosen = int(input("Enter what you want the factors of: "))

def factors(chosen, currentnum=None, numbers=None): 
    # Recursion start, always append 1 and start with 2
    if numbers is None:
        numbers = [1]
        currentnum = 2
    # We're at the last value, it's always divisible by itself so
    # append it and return
    if currentnum == chosen:
        numbers.append(currentnum)
        return numbers
    else:
        # Check if the chosen item is divisible by the current number
        if chosen % currentnum == 0:
            numbers.append(currentnum)
        # Always continue with the next number:
        currentnum += 1
        return factors(chosen, currentnum, numbers)


>>> factors(chosen)
Enter what you want the factors of: 12
[1, 2, 3, 4, 6, 12]

这不是最佳解决方案,但它使用递归并给出了正确的结果。 只是不要在函数的开头输入负值或捕获这种情况!

    # Two Pointer Approach

     ans = []
     
     
     def divisor(val):
         result = []
     
         for i in range(1, val + 1):
             ans.append(i)
     
         i = 0
         j = len(ans) - 1
     
         while i < j:
     
             if ans[i] * ans[j] == ans[-1]:
                 result.append(ans[i])
                 result.append(ans[j])
                 i += 1
             else:
                 j -= 1
     
         return sorted(result)
     
     
     print(divisor(12))


# Output

>>> [1, 2, 3, 4, 6, 12]

暂无
暂无

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

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