【问题标题】:How to split an integer into two integers that when multiplied they give the result of the first number [duplicate]如何将一个整数分成两个整数,当它们相乘时,它们会给出第一个数字的结果[重复]
【发布时间】:2017-02-20 18:37:17
【问题描述】:

所以我到处寻找,仍然无法弄清楚。

基本上我想要做的是将数字 x 拆分为两个整数,当 相乘 时,它们给出的结果是 x

例如:
Input: 10
Output: 5, 2

有没有办法在 python 中做到这一点?提前致谢。

【问题讨论】:

  • 将它们与数字 c 进行比较是什么意思。请提供输入预期输出。展示你尝试过的,...
  • 你可以将x拆分成x, 1;)
  • 如何将数字123 分成两个整数
  • 刚刚意识到编号为c 的最后一部分是不必要的。我将使用输入和预期输出进行必要的更改。另外,为什么投反对票?
  • 您要查找的词是factorization - 可汗学院

标签: python python-2.7 python-3.x


【解决方案1】:

通过这个你可以找到所有可能的组合,包括 (1, x):

import math  # Needed to generate the best range, so you have no repeated combinations.
possible_combinations = [(i, x / i) for i in range(1, int(math.ceil(x**0.5)) + 1) if x % i == 0]
for item in possible_combinations:
    print item

【讨论】:

    【解决方案2】:

    每一个整数都可以被它自己和被 1 整除。如果这个整数是合数,那么它至少会有一对其他的除数(可能是相同的,比如 4,它可以被 1,4 整除)和 2,2)。

    lim = int(math.sqrt(num))
    for i in range (1, lim):
        if num%i==0:
            print(i, int(num/i))
    

    【讨论】:

    • 如果num=4,这将只输出1 4并省略2 2,因为您执行range(1, lim),它以lim-1结尾。您应该将其更改为range(1, lim+1)。如果有人在寻找主要因素,他们会想使用range(2, lim+1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    相关资源
    最近更新 更多