- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C# Program to check if a number is prime or not
To calculate whether a number is prime or not, we have used a for a loop. Within that on every iteration, we use an if statement to find that the remainder is equal to 0, between the number itself.
for (int i = 1; i <= n; i++) { if (n % i == 0) { a++; } }
A counter a is also added, which increments only twice if the number is prime i.e. with 1 and the number itself. Therefore, if the value of a is 2, that would mean the number is prime.
Example
Let us see the complete example to check if a number is prime or not
using System; namespace Demo { class MyApplication { public static void Main() { int n = 5, a = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { a++; } } if (a == 2) { Console.WriteLine("{0} is a Prime Number", n); } else { Console.WriteLine("Not a Prime Number"); } Console.ReadLine(); } } }
Output
5 is a Prime Number
- Related Articles
- Write a C# program to check if a number is prime or not
- Python program to check if a number is Prime or not
- PHP program to check if a number is prime or not
- Bash program to check if the Number is a Prime or not
- C++ Program to Check Whether a Number is Prime or Not
- C Program to Check Whether a Number is Prime or not?
- Check if a number is Quartan Prime or not in C++
- Check if a number is Primorial Prime or not in C++
- Check if a number is a Pythagorean Prime or not in C++
- Java Program to Check Whether a Number is Prime or Not
- Check if a number is Primorial Prime or not in Python
- Python Program to Find if a Number is Prime or Not Prime Using Recursion
- Write a Golang program to check whether a given number is prime number or not
- Write a C# program to check if a number is Palindrome or not
- How to check whether a number is a prime number or not?

Advertisements