This is a C# Program to Find if a Number is Prime or Not using Recursion.
A number is said to be a prime number if it is divisible only by itself and unity.
Enter an integer as an input.
Now we create a new method named prime which uses if conditons to give the desired result.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace prime_number_method { class Program { static bool checkForPrime(int n, int i) { // Base cases if (n <= 2) return (n == 2) ? true : false; if (n % i == 0) return false; if (i * i > n) return true; // Check for next divisor return checkForPrime(n, i + 1); } static void Main(string[] args) { int n1; Console.Write(" Input any positive number : "); n1 = Convert.ToInt32(Console.ReadLine()); if (checkForPrime(n1, 2)) { Console.Write("The number {0} is a prime number.",n1); } else { Console.Write("The number {0} is not a prime number.",n1); } Console.ReadKey(); } } } |
Output:
podrias explicar el codigo?