In: Computer Science
C#
Prime factors are the combination of the smallest prime numbers, that, when multiplied together, will produce the original number. Consider the following example:
Prime factors of 4 are: 2 x 2
Prime factors of 7 are: 7
Prime factors of 30 are: 2 x 3 x 5
Prime factors of 40 are: 2 x 2 x 2 x 5
Prime factors of 50 are: 2 x 5 x 5
Create a console application with a method named PrimeFactors that, when passed an int variable as a parameter, returns a string showing its prime factors.
Use the debugging tools and write unit tests to ensure that your function works correctly with multiple inputs and returns the correct output.
SOLUTION-
I have solve the problem in C# code with comments and screenshot
for easy understanding :)
CODE-
//c# code
using System;
class HelloWorld {
public static void PrimeFactors(int num) {
Console.Write($"Prime Factors of {num} are: ");
// for even numbers
while (num % 2 == 0)
{
Console.Write("2 ");
num /= 2;
}
// if n is an odd number
for(int i = 3; i <= Math.Sqrt(num); i += 2)
{
while (num % i == 0)
{
Console.Write($"{i} ");
num /= i;
}
}
// If n is greater than 2 and Prime number
if (num > 2)
{
Console.Write($"{num} ");
}
}
static void Main() {
Console.Write("Enter a number greater than 1: ");
if (int.TryParse(Console.ReadLine(), out int num) && num
> 1)
{
PrimeFactors(num);
}
else
{
Console.WriteLine("Invalid input!!");
}
}
}
SCREENSHOT-
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------