TechieClues TechieClues
Updated date Feb 23, 2021
This code snippet explains how to check a number is a prime number or not in C#. A prime number is a number that is greater than 1 and divided by 1 or itself.
  • 2.3k
  • 0
  • 0

This code snippet explains how to check a number is a prime number or not in C#. A prime number is a number that is greater than 1 and divided by 1 or itself. For example, prime numbers are  2, 3, 5, 7, 11, 13, 17, 19, 23....

using System;

namespace SampleProgram
{
    class PrimeExample
    {
        static void Main()
        {
            // Get input
            Console.WriteLine("Enter a number:");
            int number = Convert.ToInt32(Console.ReadLine());   
            
            // Check whether the given number is prime or not
            if (IsPrimeNumber(number))            
                Console.WriteLine("{0} is a prime number", number);                            
            else            
                Console.WriteLine("{0} is not a prime number", number);            
            Console.ReadKey();
        }

        // This method returns the bool value. i.e., True for prime and False for non-prime numbers
        private static bool IsPrimeNumber(int number)
        {
            int x = 0;
            for (int i = 1; i <= number; i++)
            {
                if (number % i == 0)
                {
                    x++;
                }
            }
            if (x == 2)
            {
                return true;
            }
            return false;
        }
    }
}

Output 1:

Enter a number:
2
2 is a prime number

Output 2:

Enter a number:
8
8 is not a prime number

 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!