Divisors of a natural number

From Rosetta Code
Revision as of 21:40, 22 March 2013 by rosettacode>Paddy3118 (New draft task and Python solution.)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Divisors of a natural number is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Create a program to generate all the divisors of a given natural number.

Use it to generate and show here all the divisors of the numbers 2**(n-1) for n in the (inclusive) range [1, 16] and also for n = 31

Python

<lang python>import math from operator import mul from itertools import product from functools import reduce


def fac(n):

   \
   return the prime factors for n
   >>> fac(600)
   [5, 5, 3, 2, 2, 2]
   >>> fac(1000)
   [5, 5, 5, 2, 2, 2]
   >>>  
   
   step = lambda x: 1 + x*4 - (x//2)*2
   maxq = int(math.floor(math.sqrt(n)))
   d = 1
   q = n % 2 == 0 and 2 or 3 
   while q <= maxq and n % q != 0:
       q = step(d)
       d += 1
   res = []
   if q <= maxq:
       res.extend(fac(n//q))
       res.extend(fac(q)) 
   else: res=[n]
   return res

def fact(n):

   \
   return the prime factors and their multiplicities for n
   >>> fact(600)
   [(2, 3), (3, 1), (5, 2)]
   >>> fact(1000)
   [(2, 3), (5, 3)]
   >>> 
   
   res = fac(n)
   return [(c, res.count(c)) for c in set(res)]

def divisors(n):

   factors = fact(n)   # [(primefactor, multiplicity), ...]
   primes, maxpowers = zip(*factors)
   powerranges = (range(m+1) for m in maxpowers)
   powers = product(*powerranges)
   return (
       reduce(mul,
              (prime**power for prime, power in zip(primes, powergroup)),
              1)
       for powergroup in powers)
   

if __name__ == '__main__':

   for n in list(range(1,17)) + [31]:
       tocalc = 2**n - 1
       print("divisors(%s) = %s" % (tocalc, sorted(divisors(tocalc))))</lang>
Output:
divisors(1) = [1, 1]
divisors(3) = [1, 3]
divisors(7) = [1, 7]
divisors(15) = [1, 3, 5, 15]
divisors(31) = [1, 31]
divisors(63) = [1, 3, 7, 9, 21, 63]
divisors(127) = [1, 127]
divisors(255) = [1, 3, 5, 15, 17, 51, 85, 255]
divisors(511) = [1, 7, 73, 511]
divisors(1023) = [1, 3, 11, 31, 33, 93, 341, 1023]
divisors(2047) = [1, 23, 89, 2047]
divisors(4095) = [1, 3, 5, 7, 9, 13, 15, 21, 35, 39, 45, 63, 65, 91, 105, 117, 195, 273, 315, 455, 585, 819, 1365, 4095]
divisors(8191) = [1, 8191]
divisors(16383) = [1, 3, 43, 127, 129, 381, 5461, 16383]
divisors(32767) = [1, 7, 31, 151, 217, 1057, 4681, 32767]
divisors(65535) = [1, 3, 5, 15, 17, 51, 85, 255, 257, 771, 1285, 3855, 4369, 13107, 21845, 65535]
divisors(2147483647) = [1, 2147483647]