query for c# program
program in C# to find number enterd by user is prime or not using function.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Bhagwan AswalPosted Dec 10, 2014, 7:40 AM
Vikram AgrawalPosted Dec 10, 2014, 7:36 AM
Try this one also
private static bool IsPrime(int num)
{
if(num<=1)
return false;
if(num%2==0)
return false;
for(int i=2;i<=num/2;i++)
{
if(num%i==0)
return false;
}
return true;
}
call this method where ever you want like:
static void Main()
{
int num;
Console.Write("Enter a Number : ");
num=Convert.ToInt32(Console.ReadLine());
if(IsPrime(num))
{
Console.WriteLine(num + " is a Prime Number.");
}
else
{
Console.WriteLine(num + " is not a Prime Number.");
}
}
VulpesPosted Dec 10, 2014, 7:21 AM
Manish Kumar ChoudharyPosted Dec 10, 2014, 7:17 AM
Do it by using following lines of code.
Function
private static int CheckPrime(int number)
{
int i;
for (i = 2; i <= number - 1; i++)
{
if (number % i == 0)
{
return 0;
}
}
if (i == number)
{
return 1;
}
return 0;
}
Call :
Console.WriteLine("Enter a number");
int number = Convert.ToInt32(Console.ReadLine());
int result = CheckPrime(number);
if (result == 0)
{
Console.WriteLine("{0} is not a prime number", number);
}
else
{
Console.WriteLine("{0} is a prime number", number);
}
Console.Read();