2013-02-25 548 views
1

我想将数字表示为其因子的乘积。用于表示数字的因子数应该从2到相同数的素因子数(这是一个数字的最大可能数量)。将数字表示为其因子的乘积

例如取数24:

作为两个因素乘法数的表示是2*128*36*4等等...,的数目

表示为三个因素乘法是2*2*62*3*4等等,

作为四个因子乘法(主因子单独)的数字表示为2*2*2*3

请帮我把这个

+1

因此给出24,又该这个假设的函数返回? [2,12] [8,3] [3,8]? - 另外,我认为如果你尝试了一些事情,你会在这个问题上得到更多的回应,如果它不起作用,就会回来一个特定的问题。 – mgilson 2013-02-25 14:03:06

+0

看看[这里](http://stackoverflow.com/questions/6800193/what-is-the-most-efficient-way-of-finding-all-the-factors-of-a-number-in-蟒蛇)。这会给你的因素。那么你只需要操纵它们。 – will 2013-02-25 14:03:06

回答

0

我知道一个一些简单的和通用的算法...

如果你使用python,您可以使用字典的简化存储...

您必须检查每个小于数字平方根的素数。

现在,假设p^k将你的数字n分开,你的任务,我想是找到k。 以下是方法:

int c = 0; int temp = n; while(temp!= 0){temp/= p; c + = temp; }

以上是一个C++代码,但你会得到的想法...... 在这个循环结束时,您将有C^= K

,是的,按照遗嘱给是链接一个完美的Python实现相同的算法

0

这是一个函数,返回给定数字的所有因子,n。请注意,它会返回每一个因素,而不是特定的一对。

def factors(n): 
    """Finds all the factors of 'n'""" 
    fList, num, y, limit = [], n, 0, int(sqrt(n)) + 1 
    for factor in range(1, limit): 
     if n % factor == 0: 
      if factor not in fList: fList.append(factor) 
      y = n/factor 
      if y not in fList: fList.append(y) 
    return sorted(fList) 

例如,:

>>> factors(24) 
[1, 2, 3, 4, 6, 8, 12, 24] 
2

这将生成的该相乘以给出原始数因素所有组。它将所有产品集返回为排序元组的唯一列表。

排除1以避免无限递归。

def prime_factors(n):  
    return set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))) 

def product_sets(n): 
    return set(products(1, [], n, prime_factors(n))) 



def products(current_product, current_list, aim, factors): 

    if current_product == aim: 
     yield tuple(sorted(current_list)) 

    elif 0 < current_product < aim: 
     for factor in factors: 
      if factor != 1: 
       for product in products(current_product * factor, current_list + [factor], aim, factors): 
        yield product 


print list(product_sets(24)) 

输出:

[(4, 6), (3, 8), (2, 12), (2, 3, 4), (24,), (2, 2, 6), (2, 2, 2, 3)] 
+0

非常感谢..它帮助了我很多 – user2095966 2013-02-26 10:39:55

+0

@ user2095966 - 也许您可以将其标记为正确答案? – will 2013-02-26 13:07:45