# ==============================================================================
"""PRIME : compute all prime numbers from 2 to n"""
# ==============================================================================
__author__  = "Christophe Schlick modified by Philippe Blasi"
__version__ = "2.0" # implement the Sieve of Erathostenes
__date__    = "2022-11-12"
__usage__   = """
User input : <n> (where n:int > 1)
App output : sequence of prime numbers from 2 to n""" 
# ==============================================================================
from ezCLI import convert, grid, write_csv
# ------------------------------------------------------------------------------
def wrap(items:list, n=15) -> list:
  """convert 1D list to 2D list by wrapping every 'n' items"""
  return [items[k:k+n] for k in range(0, len(items), n)]
# ------------------------------------------------------------------------------
def prime(n:int) -> list:
  """compute all prime numbers from 2 to n"""
  primes, notprimes = [2], set() # initialize 'list of primes, and set of 
  for p in range(3, n+1, 2):
    if p not in notprimes: primes.append(p) # 'p' is prime so append to 'primes'
    for q in range(p*p, n+1, 2*p): #
      notprimes.add(q) # all odd multiples of 'p' are added to 'notprimes'
  return primes # return final list with all prime numbers up to 'n'
# ------------------------------------------------------------------------------
def main():
  """command line interaction loop"""
  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"
    # --------------------------------------------------------------------------
    primes = prime(n) # compute list of prime numbers up to 'n'
    print(grid(wrap(primes))) # show prime numbers in a grid with auto-wrapping
    # --------------------------------------------------------------------------
    write_csv('primes.csv', primes) # write list on disk as CSV file
  print('See you later...')
# ==============================================================================
if __name__ == "__main__":
  main()
# ==============================================================================
