C#Program to find prime numbers in a given range – Learn how to identify the prime number, and display prime numbers between the given rane.
Prime Number
A number which is divisible by 1 and itself is called prime number. Prime number contains only 2 factors i.e 1 and the self number.
For example, consider the number 7, for this number 1, 7 are the factors.7 is not disvisible by any other number.
Here are the first few prime numbers 2,3,5,7,11,13…
All the above numbers are divisible by 1 and the self numbers.
NOTE
2 is the even prime and remaining all prime numbers are odd numbers
C#Program to find prime numbers in a given range
Example program for generating prime numbers
Method -1 : Mathematical Approach – using k iterations
class Program
{
static void Main(string[] args)
{
int num1=3,num2=13;
Boolean flag = true; ;
Console.WriteLine("Prime numbers between "
+num1 +" and " + num2);
for (int k = num1; k <= num2; k++)
{
// loop the iterations for k times
for (int i = 2; i <k; i++)
{
if ((k % i) == 0)
{
flag = false;
break;
}
}
if (flag == true)
{
Console.WriteLine(k );
}
flag = true;
}
}
}
output
Prime numbers between 3 and 13
3
5
7
11
13
Method -2 using k/2 iterations.
class Program
{
static void Main(string[] args)
{
int num1=3,num2=13;
Boolean flag = true; ;
Console.WriteLine("Prime numbers between "
+num1 +" and " + num2);
for (int k = num1; k <= num2; k++)
{
//loop the iterations for k/2 times
for (int i = 2; i <=k/2; i++)
{
if ((k % i) == 0)
{
flag = false;
break;
}
}
if (flag == true)
{
Console.WriteLine(k );
}
flag = true;
}
}
}
}
Method -3 using square root function
class Program
{
static void Main(string[] args)
{
int num1=3,num2=13;
Boolean flag = true; ;
Console.WriteLine("Prime numbers between "
+num1 +" and " + num2);
for (int k = num1; k <= num2; k++)
{
// loop the iterations for sqrt(k) times
for (int i = 2; i <=(int)Math.Sqrt(k); i++)
{
if ((k % i) == 0)
{
flag = false;
break;
}
}
if (flag == true)
{
Console.WriteLine(k );
}
flag = true;
}
}
}