Exercise
Prime factors
Objetive
Write a C# program that displays a number (entered by the user) as a product of its prime factors. For example, 60 = 2 · 2 · 3 · 5
(Hint: it can be easier if the solution is displayed as 60 = 2 · 2 · 3 · 5 · 1)
Example Code
using System; // Import the System namespace to use basic classes like Console
class Program // Define the main class of the program
{
static void Main() // The entry point of the program
{
// Ask the user to enter a number
Console.Write("Enter a number: "); // Display prompt for the number input
int number = int.Parse(Console.ReadLine()); // Read the input as an integer
int originalNumber = number; // Store the original number for display later
string result = originalNumber + " = "; // Start the result string
// Check for divisibility by 2 first (for efficiency)
while (number % 2 == 0) // While the number is divisible by 2
{
result += "2 · "; // Append '2' to the result string
number /= 2; // Divide the number by 2
}
// Now check for odd factors starting from 3
for (int i = 3; i <= Math.Sqrt(number); i += 2) // Only check odd numbers (i += 2)
{
while (number % i == 0) // While the number is divisible by 'i'
{
result += i + " · "; // Append the factor 'i' to the result string
number /= i; // Divide the number by 'i'
}
}
// If the remaining number is greater than 2, it must be prime
if (number > 2)
{
result += number + " · "; // Append the last prime factor
}
// To remove the final " · " from the result string
result = result.Substring(0, result.Length - 2); // Remove last two characters
// Display the result
Console.WriteLine(result); // Print the prime factorization of the number
}
}