C# Program to Find the Largest Prime Factor of a Number

This is a C# Program to check whether the given number is a prime number if so then display its largest factor.

Problem Description

This C# Program Checks Whether the Given Number is a Prime number if so then Display its Largest Facor.

Problem Solution

Here first the number that is obtained is checked whether the number is prime or not and then the largest factor of it is displayed.

Program/Source Code

Here is source code of the C# Program to Check Whether the Given Number is a Prime number if so then Display its Largest Factor. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Check Whether the Given Number is a Prime number if so then 
 * Display its Largest Factor
 */
using System;
namespace example
{
    class prime
    {
        public static void Main()
        {
            Console.Write("Enter a Number : ");
            int num;
            num = Convert.ToInt32(Console.ReadLine());
            int k;
            k = 0;
            for (int i = 1; i <= num; i++)
            {
                if (num % i == 0)
                {
                    k++;
                }
            }
            if (k == 2)
            {
                Console.WriteLine("Entered Number is a Prime Number and " + 
                                  "the Largest Factor is {0}",num);
            }
            else
            {
                Console.WriteLine("Not a Prime Number");
            }
            Console.ReadLine();
        }
    }
}
Program Explanation

This C# program we are reading a number using ‘num’ variable. Compute the modulus of the value of ‘num’ variable by the value of ‘i’ variable is equal to 0. If the condition is true, then execute the statement. Print the largest factor among the prime number.

advertisement
advertisement
Runtime Test Cases
 
Enter a Number : 23
Entered Number is a Prime Number and the Largest Factor is 23

Sanfoundry Global Education & Learning Series – 1000 C# Programs.

If you wish to look at all C# Programming examples, go to 1000 C# Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.