Q. 1 What is Prime Number?
Answer : A prime number (or a prime) is a natural number greater than 1 that has no positive divisors other than 1 and itself.
Q. 2 Write a programmer in C# to check number is prime or not ?
Answer : The following code snippet to check prime number or not.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a number");
int number = Convert.ToInt32(Console.ReadLine());
int result = Check_Prime(number);
if (result == 0)
{
Console.WriteLine("{0} is not a prime number", number);
}
else
{
Console.WriteLine("{0} is a prime number", number);
}
Console.Read();
}
private static int Check_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;
}
}
Another Program is :
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter the number in which you want to find the prime no");
int a = Convert.ToInt32(Console.ReadLine());
bool isPrime = true;
for (int i = 1; i <= a; i++)
{
for (int j = 2; j <= a; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.WriteLine("Prime:" + i);
}
isPrime = true;
}
Console.ReadLine();
}
}
Another Program is :
class Math
{
static bool IsPrimeNumber(int num)
{
bool bPrime = true;
int factor = num / 2;
for (int i = 2; i <= factor; i++)
{
if ((num % i) == 0)
bPrime = false;
}
return bPrime;
}
static void Main(string[] args)
{
Console.WriteLine("List of prime numbers between 0 - 15");
for (int i = 0; i < 15; i++)
{
if (IsPrimeNumber(i) == true)
Console.WriteLine(i);
}
Console.WriteLine();
Console.Read();
}
}
0 comments:
Post a Comment