Write a C# program to check if a number is prime or not

CsharpProgrammingServer Side Programming

To calculate whether a number is prime or not, we have used a loop and within that on every iteration, we have an if statement to find that the remainder is equal to 0, between the number itself.

for (int i = 1; i <= n; i++) {
   if (n % i == 0) {
      a++;
   }
}

A counter a is also added, which increments only twice if the number is prime i.e. with 1 and the number itself. Therefore, if the value of a is 2, that would mean the number is prime.

Let us see the complete example to check if a number is prime or not −

Example

 Live Demo

using System;
namespace Demo {
   class MyApplication {
      public static void Main() {
         int n = 17, a = 0;

         for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
               a++;
            }
         }

         if (a == 2) {
            Console.WriteLine("{0}: Prime Number", n);
         } else {
            Console.WriteLine("{0}: Not a Prime Number");
         }
         Console.ReadLine();
      }
   }
}

Output

17: Prime Number
raja
Published on 06-Aug-2018 06:15:39
Advertisements