# ==============================================================================
"""PRIMEFACTO : compute all prime factorizations for numbers from 2 to n"""
# ==============================================================================
__author__  = "Christophe Schlick modified by Philippe Blasi"
__version__ = "1.0" # input CSV file and output INI file
__date__    = "2022-11-12"
__usage__   = """
User input : <n> (where n:int > 1)
App output : sequence of all prime factorizations for numbers from 2 to n""" 
# ==============================================================================
from ezCLI import convert, read_csv, write_ini
# ------------------------------------------------------------------------------
def primefacto(n:int, primes:list) -> dict:
  """compute all prime factorizations for numbers from 2 to n"""
  factos = {} # create empty dictionary to store prime factorizations
  for p in range(2, n+1): # loop over numbers to factorize
    factos[p] = [] # insert empty factor list for number 'p'
    r = p # initialize remaining ratio before starting factorization
    for q in primes: # loop over prime numbers to find all factors for 'p'
      if q > r: break # all factors for 'p' have been found
      while r%q == 0: # 'q' is a factor for 'p'
        r = r//q; factos[p].append(q) # update 'r' and append 'q' to list
  return factos # return final dictionary with all factorizations up to 'n'
# ------------------------------------------------------------------------------
def main():
  """parse 'command' as integer 'n' before calling 'prime(n)'"""
  primes = read_csv('primes.csv') # read CSV file generated by A8_prime.py
  print(f"{'-'*80}\n{__doc__}{__usage__}\n{'-'*80}") # show info (doc and usage)
  while True: # user interaction loop
    command = input("Enter value for <n> : ") # wait for user input
    if command == '': break # break interaction loop if user input is empty
    n = convert(command) # analyze user input and convert to appropriate type
    assert type(n) is int and n > 1, "<n> must be an integer and greater than 1"
    # --------------------------------------------------------------------------
    factos = primefacto(n, primes) # compute all prime factorizations
    #print(factos) # print raw dictionary without post-processing
    # --------------------------------------------------------------------------
    # post-process the dictionary to obtain a more intuitive display
    for p in factos: factos[p] = ' * '.join(str(q) for q in factos[p])
    for p in factos: print(f"{p} = {factos[p]}")
    # --------------------------------------------------------------------------
    write_ini('factos.ini', factos) # write dictionary on disk as INI file
  print('See you later...')
# ==============================================================================
if __name__ == "__main__":
  main()
# ==============================================================================
