Group
C# Basic Data Types Overview
Objective
1. Prompt the user to enter an integer number.
2. Use a loop to find and extract the prime factors of the number.
3. Display the factors as a multiplication sequence.
4. Include `1` at the end of the factorization for consistency.
5. Ensure the program handles invalid or negative inputs gracefully.
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
Example C# Exercise
Show C# Code
using System;
class Program
{
static void Main()
{
// Ask the user for an integer input
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
// Store the original number for output
int originalNumber = number;
// Start displaying the factorization
Console.Write(originalNumber + " = ");
// Find and print the prime factors
bool firstFactor = true;
// Divide by 2 while it's a factor
while (number % 2 == 0)
{
Console.Write(firstFactor ? "2" : " · 2");
number /= 2;
firstFactor = false;
}
// Check odd numbers from 3 onwards
for (int i = 3; i * i <= number; i += 2)
{
while (number % i == 0)
{
Console.Write(firstFactor ? i.ToString() : " · " + i);
number /= i;
firstFactor = false;
}
}
// If a prime number remains (greater than 1), print it
if (number > 1)
{
Console.Write(firstFactor ? number.ToString() : " · " + number);
}
// Append " · 1" for formatting consistency
Console.WriteLine(" · 1");
}
}
Output
//Example 1: User enters 60
Enter a number: 60
60 = 2 · 2 · 3 · 5 · 1
//Example 2: User enters 84
Enter a number: 84
84 = 2 · 2 · 3 · 7 · 1
//Example 3: User enters 97 (a prime number)
Enter a number: 97
97 = 97 · 1