Answers for "c# how to get a prime number"

C#
2

get prime number c#

// Assuming that the number passed is higher than 1.


// This function will check if the number is prime by using all the previous
// numbers. There's no need to check further than the square root 
// Returns true or false.
public static bool isPrime(int number)
        {
            double sqrNum = Math.Sqrt(number);
            for (int i = 2; i <= sqrNum; i++) if (number % 2 == 0) return false;
            return true;
        }


// This function is essentially the same
// but will only compare with numbers from a prime number list
public static bool isPrime(int number, int[] primeList) 
       {
            double sqrNum = Math.Sqrt(number);

            foreach(int prime in primeList) { 
                if (prime > sqrNum) return true;
                else if (number % prime==0) return false;
            }
            return true;
       }
// You can expand your primeList using any of the functions, 
//to better use the second function.
Posted by: Guest on August-06-2021
-1

how to check prime number in c#

using System;  
  public class PrimeNumberExample  
   {  
     public static void Main(string[] args)  
      {  
          int n, i, m=0, flag=0;    
          Console.Write("Enter the Number to check Prime: ");    
          n = int.Parse(Console.ReadLine());  
          m=n/2;    
          for(i = 2; i <= m; i++)    
          {    
           if(n % i == 0)    
            {    
             Console.Write("Number is not Prime.");    
             flag=1;    
             break;    
            }    
          }    
          if (flag==0)    
           Console.Write("Number is Prime.");       
     }  
   }
Posted by: Guest on May-03-2021

C# Answers by Framework

Browse Popular Code Answers by Language