![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Different Methods to find Prime Numbers in C#
The following are the two ways through which you can find a prime number in C#.
Check Prime Number using for loop
using System; namespace Program { class Demo { public static void Main() { int n =7; int a; a = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { a++; } } if (a == 2) { Console.WriteLine("Prime Number"); } else { Console.WriteLine("Not a Prime Number"); } Console.ReadLine(); } } }
Output
Prime Number
Check Prime Number using a function in C#
using System; namespace Program { class Demo { static void Main(string[] args) { int n = 7; int res = primeFunc(n); if (res == 0) { Console.WriteLine("Not a prime number", n); } else { Console.WriteLine("Prime number", n); } Console.Read(); } private static int primeFunc(int n) { int i; for (i = 2; i <= n - 1; i++) { if (n % i == 0) { return 0; } } if (i == n) { return 1; } return 0; } } }
Output
Prime number
Advertisements