Resources » Code Snippets » C# Syntax

Check if a number is prime or not!


Updated: Category: C# Syntax
Author: Member Level: SilverPoints: 10



using System;
using System.Collections.Generic;
using System.Text;

namespace odd_number
{
class Program
{
static void Main(string[] args)
{
int num1;

Console.WriteLine("Accept number");
num1 = Convert.ToInt32(Console.ReadLine());
for (int a = 1; a <=(num1 / 2); a++ )
{
if (num1%a!=0)
{
Console.WriteLine("Number is a prime number");
break;
}

else
{
Console.WriteLine("Number is not prime number");
break;

}


}
Console.ReadLine();
}
}
}


Did you like this resource? Share it with your friends and show your love!

Responses to "Check if a number is prime or not!"
Author: Nathan Stanford  14 May 2010   Member Level: Bronze   Points : 1
This code is incorrect. I put in the number 239 and it is a prime number and yet this program says it is not a prime number.


Author: Asif Huddani  15 May 2010   Member Level: Gold   Points : 2
Hi,

using System;
using System.Collections.Generic;
using System.Text;

namespace Exercise_1
{
class Prime
{
public void Prime_Number(int number)
{
int i;
for (i = 2; i < number; i++)
{
if (number % i == 0)
{
Console.WriteLine("{0} is not a prime number", number);
break;
}
}
if(i == number)
{
Console.WriteLine("{0} is a prime number", number);
}
}
static void Main(string[] args)
{
int num;
Console.WriteLine("Enter the number: ");
num = Convert.ToInt32(Console.ReadLine());
Prime p = new Prime();
p.Prime_Number(num);
}
}
}



Author: mox shah  17 May 2010   Member Level: Gold   Points : 2
hello



using System;

using System.Collections.Generic;

using System.Text;



namespace prime

{

class Program

{

static void Main(string[] args)

{

int num;

int result;

int i, j;



Console.WriteLine("Untill what number u want to show prime number?");

num = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("The prime number between o and ur number are:");

if (num == 2)

Console.WriteLine("2");



else
{



Console.WriteLine("2");

for (i = 3; i <= num; i++)

{

for (j = 2; j <=num / 2; j++)

{

result = i % j;

if (result!=0)

Console.WriteLine(i);



}
}

Console.ReadLine();

}

}

}

}




Feedbacks      

Post Comment:




  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:   Sign In to fill automatically.
    Email: (Will not be published, but required to validate comment)



    Type the numbers and letters shown on the left.


    Submit Article     Return to Article Index
    Subscribe to Subscribers
    Active Members
    Today
      Last 7 Daysmore...

      Awards & Gifts
      Talk to Webmaster Tony John
       
      Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India