Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to check if a number is prime in C#

2 Answers

0 votes
using System;

public class Program
{
    static bool isPrime(int n) {
        if (n == 0) return false;
        if (n == 1) return false;
        
        for (int i = 2; i <= (int)Math.Sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        
        return true;
    }
    
    static void Main(string[] args) {
        int n = 0;
 
        Random rnd = new Random();
 
        for (int i = 0; i < 20; i++) {
            n = rnd.Next(1, 100);
            if (isPrime(n)) {
                Console.WriteLine("{0} - Prime", n);
            }
            else {
                Console.WriteLine("{0} - NOT Prime", n);
            }
        }
    }
}



/*
run:

94 - NOT Prime
81 - NOT Prime
47 - Prime
78 - NOT Prime
12 - NOT Prime
99 - NOT Prime
12 - NOT Prime
11 - Prime
99 - NOT Prime
59 - Prime
28 - NOT Prime
83 - Prime
86 - NOT Prime
67 - Prime
14 - NOT Prime
75 - NOT Prime
66 - NOT Prime
72 - NOT Prime
59 - Prime
72 - NOT Prime
   
*/


answered Apr 10, 2014 by avibootz
edited May 17, 2024 by avibootz
0 votes
using System;
 
class Program
{
    static bool isPrime(int n) {
        if (n < 2 || (n % 2 == 0 && n != 2)) {
            return false;
        }
      
        int count = (int)Math.Floor(Math.Sqrt(n));
        for (int i = 3; i <= count; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
    static void Main() {
        int n = 97;
 
        if (isPrime(n)) {
            Console.Write("Prime number");
        } else {
            Console.Write("Not prime number");
        }
    }
}
 
 
 
 
/*
run:
  
Prime number
  
*/

 



answered May 17, 2024 by avibootz
...