C# Program to Check for Prime Numbers: An Efficient Algorithm

Learn how to determine if a number is prime in C#. This tutorial provides a clear and efficient algorithm, demonstrating how to check for divisibility and identify prime numbers, offering a practical solution for number theory and related programming tasks.



Checking for Prime Numbers in C#

A prime number is a whole number greater than 1 that's only divisible by 1 and itself. This program demonstrates how to check if a given number is prime using C#.

Understanding Prime Numbers

Prime numbers are numbers greater than 1 that are only divisible by 1 and themselves. Examples: 2, 3, 5, 7, 11, 13, ...

C# Code for Prime Number Check


using System;

public class PrimeNumberExample {
    public static void Main(string[] args) {
        Console.Write("Enter a number: ");
        int n = int.Parse(Console.ReadLine());
        int m = n / 2, i, flag = 0;
        // ... (for loop to check if n is divisible by any number from 2 to m) ...
    }
}

Explanation

The program takes an integer as input from the user. It calculates half of the number (`m`). It iterates from 2 up to `m`, checking if the input number is divisible by any number in that range. If it finds a divisor, it means the number is not prime, so it prints a message and exits the loop. If the loop completes without finding any divisors, the number is prime.