Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements