Prime Numbers in C#
Sep 03, 2024 pm 03:35 PMPrime Numbers are the whole numbers greater than 1 that can be the factors for only the number 1 and for itself, i.e. the number ‘n’ can be divisible only by 1 or by ‘n’ itself. A few of the well-known prime numbers are 2, 3, 5, 7, 9, 11, 13, 17, 19, 23, etc. C# programs, in the subject of prime numbers, can be used for finding if the given number is a prime number or not, and for displaying all the prime numbers within a given range. This can be achieved in C# programs by defining logics using various loops and conditional statements, such as the for loop, if condition, if else condition, while loop, etc.
Examples of Prime Numbers in C#
Let us try to conceptualize prime numbers with the following programming examples.
Example #1
C# program to print the list of all prime numbers between 1 to 100.
Code:
using?System; using?System.Collections.Generic; using?System.Linq; using?System.Text; using?System.Threading.Tasks; namespace?ConsoleApplication1 { class?Program { static?void?Main(string[] args) // this function defines the entry point { bool?Prime = true; Console.WriteLine("Prime Numbers between 1 to 100 : "); for?(int?a = 2; a <= 100; a++) //upper limit and lower limit are defined { for?(int?b = 2; b <= 100; b++)// base logic for the primality { if?(a != b && a % b == 0) //modulo operators employed { Prime = false; break; } } if?(Prime) { Console.Write("\t"?+ a); //printing the correct variable } Prime = true; } Console.ReadKey(); //hold the output screen } } }
Output:
Program Explanation:?The above program is a classic example of the use of loops and conditional operators for determining the prime numbers in a fixed range of numbers. The program above uses a lower limit of Natural number i.e.2 ?defining ‘a(chǎn)’ ?as a natural number in the range of 2 ranging to 99 with the post-operation increment of 1, the next step uses a variable ‘b’ with the similar range but bound to a condition in its upper limit is always less than ‘a(chǎn)’. The loop then passes through the range and uses the natural operation of modulo on the variable a by the divisor b.
The modulo operator returns 0 if a is perfectly divisible by b?indicating the fact that b as a smaller natural number is a factor for the composite number a. We use a Boolean parameter Prime for a flag in case we are receiving the value of a % b ?not equal to zero. Now we employed the conditional operator to print the number in the output console in case we received the number as a prime number.
Example #2
Checking for prime numbers with for?loop
Code:
using?System; using?System.Collections.Generic; using?System.Linq; using?System.Text; using?System.Threading.Tasks; namespace?ConsoleApplication1 { class?Program { public?static?void?Main(string[] args) { int?n, a, m = 0, PrimeIndicator = 0; Console.Write("Please enter the number to check for Primality: "); n = int.Parse(Console.ReadLine()); m = n / 2; for?(a = 2; a <= m; a++) { if?(n % a == 0) { Console.Write("The entered number is not ?a Prime number ."); PrimeIndicator = 1; break; } } if?(PrimeIndicator == 0) Console.Write("The entered number is a Prime number . "); } } }
Output:
Program Explanation:?The program described above uses for loop for defining the conditions for primality. The input read field captures the user input an assigns to the variable n, the counter parses from the value of 2 to a value of n-1 and tests the conditions of divisibility to determine the number is prime or not.the additional feature involved in the program employs the use of a variable m with value of n/2 or exactly half of the initial user input, the program parses the loop over only up to a value of m.
Example #3
Primality using a while loop.
Code:
using?System; using?System.Collections.Generic; using?System.Linq; using?System.Text; using?System.Threading.Tasks; namespace?ConsoleApplication1 { class?Program { static?void?Main(string[] args) { int?n, i, a; Console.Write("Enter any number: "); n = Convert.ToInt32(Console.ReadLine()); // read the user input a = 0; i = 2; while?(i <= n / 2) { if?(n % i == 0) { a = 1; break; } i++; } if?(a == 0) Console.WriteLine(n + " Prime Number as there are no factors"); else Console.WriteLine(n + " not a Prime Number "); Console.ReadLine(); } } }
Output:
Program Explanation:?The program above illustrates the process of determining the primality of a number using while loop in C#. The program above reads the user input from using the control reading command and parses over the range 2 to a value of user input divided by 2 to determine the value of a flag used to test the primality of a number. The value is assigned inside the loop and displays the result according to the value of a.
Conclusion
Prime numbers thus are natural numbers greater than 1 with only factors being 1 and itself. A composite number can be broken down as a factor of primes, these numbers are called prime factors. The various programs illustrated above provide us with ways of implementing the primality of any number using the loops like do, for, while loops. Although the logic behind implementation of all the above programs is by finding the factors of a number by operating it with modulo operator yet the implementation of the same is controlled at various points depending upon the choice of the loop.
The above is the detailed content of Prime Numbers in C#. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Random Number Generator in C#. Here we discuss how?Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

There are several ways to modify XML formats: manually editing with a text editor such as Notepad; automatically formatting with online or desktop XML formatting tools such as XMLbeautifier; define conversion rules using XML conversion tools such as XSLT; or parse and operate using programming languages ??such as Python. Be careful when modifying and back up the original files.

Guide to Palindrome in C#. Here we discuss the introduction and logic behind palindrome in C#? along with the various methods with its code.
