How to resolve the algorithm Abundant odd numbers step by step in the Python programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Abundant odd numbers step by step in the Python programming language

Table of Contents

Problem Statement

An Abundant number is a number n for which the   sum of divisors   σ(n) > 2n, or,   equivalently,   the   sum of proper divisors   (or aliquot sum)       s(n) > n.

12   is abundant, it has the proper divisors     1,2,3,4 & 6     which sum to   16   ( > 12 or n);        or alternately,   has the sigma sum of   1,2,3,4,6 & 12   which sum to   28   ( > 24 or 2n).

Abundant numbers are common, though even abundant numbers seem to be much more common than odd abundant numbers. To make things more interesting, this task is specifically about finding   odd abundant numbers.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Abundant odd numbers step by step in the Python programming language

The Python code defines functions and a main() function to explore abundant odd numbers. Here's a breakdown:

  1. Importing Libraries: It imports the sqrt function from the math module.

  2. Function divisorSum: This function calculates the sum of divisors for a given integer n. It iterates through divisors of n, including the square root, and adds them to the sum.

  3. Main Function:

    • Printing the First 25 Abundant Odd Numbers: It iterates through odd numbers and checks if the sum of divisors is greater than the number. If true, it prints the number with its divisor sum.
    • Finding the 1000th Abundant Odd Number: It keeps iterating and printing until it finds the 1000th abundant odd number.
    • Finding the First Abundant Odd Number Greater Than 1 Billion: It searches for the first abundant odd number greater than 1 billion and prints it with its divisor sum.
  4. Helper Functions:

    • abundantTuple: Returns a tuple containing the number and its divisor sum if the number is abundant (divisor sum > number); otherwise, it returns an empty list.
    • divisorSum: Same as the function defined earlier.
    • enumFromThen: Generates an infinite stream of integers starting from m with an interval of n-m.
    • concatMap: Applies a function to each element in a list and concatenates the results into a new list.
    • take: Returns the first n elements from a list.
  5. Execution: The code calls the main() function, which performs the desired operations and prints the results.

Overall, the code explores abundant odd numbers, providing the first 25, the 1000th, and the first one greater than 1 billion, along with their respective divisor sums.

Source code in the python programming language

#!/usr/bin/python
# Abundant odd numbers - Python

oddNumber  = 1
aCount  = 0
dSum  = 0
 
from math import sqrt
 
def divisorSum(n):
    sum = 1
    i = int(sqrt(n)+1)
 
    for d in range (2, i):
        if n % d == 0:
            sum += d
            otherD = n // d
            if otherD != d:
                sum += otherD
    return sum
 
print ("The first 25 abundant odd numbers:")
while aCount  < 25:
    dSum  = divisorSum(oddNumber )
    if dSum  > oddNumber :
        aCount  += 1
        print("{0:5} proper divisor sum: {1}". format(oddNumber ,dSum ))
    oddNumber  += 2
 
while aCount  < 1000:
    dSum  = divisorSum(oddNumber )
    if dSum  > oddNumber :
        aCount  += 1
    oddNumber  += 2
print ("\n1000th abundant odd number:")
print ("    ",(oddNumber - 2)," proper divisor sum: ",dSum)
 
oddNumber  = 1000000001
found  = False
while not found :
    dSum  = divisorSum(oddNumber )
    if dSum  > oddNumber :
        found  = True
        print ("\nFirst abundant odd number > 1 000 000 000:")
        print ("    ",oddNumber," proper divisor sum: ",dSum)
    oddNumber  += 2


'''Odd abundant numbers'''

from math import sqrt
from itertools import chain, count, islice


# abundantTuple :: Int -> [(Int, Int)]
def abundantTuple(n):
    '''A list containing the tuple of N and its divisor
       sum, if n is abundant, or an empty list.
    '''
    x = divisorSum(n)
    return [(n, x)] if n < x else []


#  divisorSum :: Int -> Int
def divisorSum(n):
    '''Sum of the divisors of n.'''
    floatRoot = sqrt(n)
    intRoot = int(floatRoot)
    blnSquare = intRoot == floatRoot
    lows = [x for x in range(1, 1 + intRoot) if 0 == n % x]
    return sum(lows + [
        n // x for x in (
            lows[1:-1] if blnSquare else lows[1:]
        )
    ])


# TEST ----------------------------------------------------
# main :: IO ()
def main():
    '''Subsets of abundant odd numbers.'''

    # First 25.
    print('First 25 abundant odd numbers with their divisor sums:')
    for x in take(25)(
            concatMap(abundantTuple)(
                enumFromThen(1)(3)
            )
    ):
        print(x)

    # The 1000th.
    print('\n1000th odd abundant number with its divisor sum:')
    print(
        take(1000)(
            concatMap(abundantTuple)(
                enumFromThen(1)(3)
            )
        )[-1]
    )

    # First over 10^9.
    print('\nFirst odd abundant number over 10^9, with its divisor sum:')
    billion = (10 ** 9)
    print(
        take(1)(
            concatMap(abundantTuple)(
                enumFromThen(1 + billion)(3 + billion)
            )
        )[0]
    )


# GENERAL FUNCTIONS ---------------------------------------

# enumFromThen :: Int -> Int -> [Int]
def enumFromThen(m):
    '''A non-finite stream of integers
       starting at m, and continuing
       at the interval between m and n.
    '''
    return lambda n: count(m, n - m)


# concatMap :: (a -> [b]) -> [a] -> [b]
def concatMap(f):
    '''A concatenated list over which a function f
       has been mapped.
       The list monad can be derived by using an (a -> [b])
       function which wraps its output in a list (using an
       empty list to represent computational failure).
    '''
    return lambda xs: (
        chain.from_iterable(map(f, xs))
    )


# take :: Int -> [a] -> [a]
def take(n):
    '''The prefix of xs of length n,
       or xs itself if n > length xs.
    '''
    return lambda xs: (
        list(islice(xs, n))
    )


if __name__ == '__main__':
    main()


  

You may also check:How to resolve the algorithm Singly-linked list/Element definition step by step in the Elena programming language
You may also check:How to resolve the algorithm Faulhaber's formula step by step in the J programming language
You may also check:How to resolve the algorithm Elliptic Curve Digital Signature Algorithm step by step in the C++ programming language
You may also check:How to resolve the algorithm User input/Text step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Draw a pixel step by step in the Lua programming language