
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Write a C# program to check if a number is prime or not
To calculate whether a number is prime or not, we have used a loop and within that on every iteration, we have 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.
Let us see the complete example to check if a number is prime or not −
Example
using System; namespace Demo { class MyApplication { public static void Main() { int n = 17, a = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { a++; } } if (a == 2) { Console.WriteLine("{0}: Prime Number", n); } else { Console.WriteLine("{0}: Not a Prime Number"); } Console.ReadLine(); } } }
Output
17: Prime Number
- Related Articles
- 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
- Write a Golang program to check whether a given number is prime number or not
- Bash program to check if the Number is a Prime or not
- Write a C# program to check if a number is Palindrome or not
- C++ Program to Check Whether a Number is Prime or Not
- C Program to Check Whether a Number is Prime or not?
- Java 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 Python
- Check if a number is Primorial Prime or not in C++
- Check if a number is a Pythagorean Prime or not in C++
- Python Program to Find if a Number is Prime or Not Prime Using Recursion
- How to check whether a number is a prime number or not?

Advertisements