//  *********************************************************************************************
//  Description      : C Program to find prime factors of a Number
//  Project Version  : v1.0
//  Project          : [BCDC] Microtec Academy Course: Building a RISC-V CPU with SystemVerilog
//  -----
//  Copyright (c)    : 2025 Fraunhofer IIS, Department IDS
//  Created          : 15.Oct.2025  by Hussein Elzomor
//  Last Modified    : 15.Oct.2025  by Hussein Elzomor
//  -----
//  HISTORY          : Date         By         Comments
//                     -----------  ---------  -------------------------------------------------
//  *********************************************************************************************



asm(".global _start, halt; _start: lui sp 0x2; addi sp sp -4; jal main");

int main()
{
  int i, iModulo, j, Number, NumberModulo, isPrime, Prime; // Create variables
  Number = 39;                                             // Set initial value for Number to be factorized
  Prime = 0;                                               // Set initial value for Prime to be printed
  for (i = 2; i <= Number; i++)                            // Iterate over i from 2 to Number, all possible numbers excluding 1 & 0
  {
    NumberModulo = Number;
    while (NumberModulo > 0)                               // Calculate Number % i using subtraction and store in NumberModulo
    {
      NumberModulo -= i;
    }
    if (NumberModulo == 0)                                 // If Number % i == 0, it is possible that it's a prime number
    {
      isPrime = 1;
      for (j = 2; j <= i / 2; j++)                         // Iterate over j from 2 to i/2
      {
        iModulo = i;
        while (iModulo > 0)                                // Calculate i % j using subtraction and store in iModulo
        {
          iModulo -= j;
        }
        if (iModulo == 0)                                  // If i % j == 0, it is not a prime number
        {
          isPrime = 0;
          break;
        }
      }
      if (isPrime == 1)                                    // Print i if i is a prime number
      {
        Prime = i;                                         // Set variable Prime to the prime number. Used for printing in the TB upon change
      }
    }
    }
  return 0;                                                // End the main function and return 0 on success
}
