Defintion
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Here is a c# source code to check a given number is prime or not:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleDemoApp
{
class test
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number to check its a prime :-");
int num = Convert.ToInt32(Console.ReadLine());
int result = CheckFor_Prime(num);
if (result == 0)
{
Console.WriteLine("{0} is not a prime number!", num);
}
else
{
Console.WriteLine("{0} is a prime number", num);
}
Console.Read();
}
private static int CheckFor_Prime(int number)
{
int i;
for (i = 2; i <= number - 1; i++)
{
if (number % i == 0)
{
return 0;
}
}
if (i == number)
{
return 1;
}
return 0;
}
}
}
Ouput:-
Enter a number to check its a prime :- 67
67 is not a prime number!
Enter a number to check its a prime :-77
77 is a prime number
Enter a number to check its a prime :- 29
29 is not a prime number!
Here is a source code example to print prime number between 1 and 100 :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleDemoApp
{
class test
{
static void Main(string[] args)
{
bool isPrimeNum = true;
Console.WriteLine("Prime Numbers between 1 and 100 are:- ");
for (int i = 2; i <= 100; i++)
{
for (int j = 2; j <= 100; j++)
{
if (i != j && i % j == 0)
{
isPrimeNum = false;
break;
}
}
if (isPrimeNum)
{
Console.Write("\t" + i);
}
isPrimeNum = true;
}
Console.ReadKey();
}
}
}
Outtput:-
Prime Numbers :
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
No comments:
Post a Comment