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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to check if a number is prime in Java

2 Answers

0 votes
import java.util.Random;

public class MyClass {
    static Boolean isPrime(int n) {
        if (n == 0) return false;
        if (n == 1) return false;
        
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        
        return true;
    }
    
    public static void main(String args[]) {
       try {
        
            Random rnd = new Random();

            for (int i = 0; i < 20; i++) {
                int n = rnd.nextInt(100) + 1;
                if (isPrime(n)) {
                    System.out.format("%d - Prime\n", n);
                }
                else {
                    System.out.format("%d - NOT Prime\n", n);
                }
            }
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }  
    }
}
 
 
 
/*
run:
 
5 - Prime
29 - Prime
91 - NOT Prime
92 - NOT Prime
56 - NOT Prime
38 - NOT Prime
15 - NOT Prime
15 - NOT Prime
80 - NOT Prime
71 - Prime
57 - NOT Prime
85 - NOT Prime
47 - Prime
47 - Prime
56 - NOT Prime
85 - NOT Prime
99 - NOT Prime
71 - Prime
17 - Prime
61 - Prime
 
*/


answered May 19, 2015 by avibootz
edited May 18, 2024 by avibootz
0 votes
public class MyClass {
    static boolean 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;
    }
     
    public static void main(String args[]) {
        int n = 97;
 
        if (isPrime(n)) {
            System.out.println("Prime number");
        } else {
            System.out.println("Not prime number");
        }
    }
}
 
 
 
 
/*
run:
    
Prime number
    
*/

 



answered May 18, 2024 by avibootz
...