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

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

Last updated:11/19/2021 10:40:50 PM

1 Answers

Ashutosh Kumar Verma
Ashutosh Kumar Verma

Prime Number:

  A prime number is a number that divided by self or 1 and no other number can divide that is called a prime number. 1 is not a prime number because there is must be divided by two number that are 1 and that number.

Ex-      2,3,5,7,11,13,17… etc.

Program:

using System;					

public class Program
{
 public static void Main()
 {
 int num,I;
 int temp=0;
 Console.WriteLine(“Enter a number to check whether prime or not);
 num=int.Parse(Console.ReadLine());
  for(i=2;i<=num/2;i++)
  {
   if(num%i==0)
   {
    temp=temp+1;
   }
  }
  if(temp==0)
  {
  Console.WriteLine('is Prime');
  }else
  {
  Console.WriteLine('not prime');
  }
 }
}

 Output:

 Enter a number to check whether prime or not      7

7 is prime

Print all prime number between 1 to 100.

Program:

using System;					

public class Program
{
 public static void Main()
 {
 int num,i,j;
  int temp=0, res;
  for(num=2;num<=100;num++)
  {
  for(i=2;i<=num/2;i++)
  {
   if(num%i==0)
   {
    temp=temp+1;
   }
  }
   if(temp==0)
      {
    Console.Write(' '+num);
   }else
   {
    temp=0;
   }
 }
 }
}

Output:

  2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97


Answer