Skip to content
The Chat Archive
gpt-4o-2024-08-06· OpenAI WildChat-4.8M (AI2)

Write java code to print prime number till 100

  1. User

    Write java code to print prime number till 100

  2. Assistant

    To print prime numbers up to 100 in Java, you can write a simple program using a loop to check if each number is prime. Here's an example:

    public class PrimeNumbers {
    
        public static void main(String[] args) {
            // Loop through numbers from 2 to 100
            for (int num = 2; num <= 100; num++) {
                if (isPrime(num)) {
                    System.out.print(num + " ");
                }
            }
        }
    
        // Method to check if a number is prime
        public static boolean isPrime(int number) {
            if (number <= 1) {
                return false;
            }
            // Check for factors from 2 to the square root of the number
            for (int i = 2; i <= Math.sqrt(number); i++) {
                if (number % i == 0) {
                    return false; // Not a prime number if divisible by 'i'
                }
            }
            return true; // A prime number if no factors are found
        }
    }
    

    Explanation:

    • Loop from 2 to 100: The outer loop iterates through each number from 2 to 100 since 1 is not considered a prime number.

    • Check Prime Status: The isPrime method determines if a number is prime. It returns false if the number has any divisors other than 1 and itself.

    • Efficiency with Square Root: Instead of checking divisibility up to the number itself, the method checks up to the square root of the number. This reduces the number of iterations needed, making the algorithm more efficient.

    • Output: If a number is prime, it is printed followed by a space.

    Run this code, and you'll see all prime numbers from 2 to 100 printed in a single line.