Prime Number Program

Definition & Explanation

We aim to determine if a positive integer is a prime number. The task involves crafting a Java program that examines factors other than 1 and the number itself to assess whether the given number is prime. The code will investigate potential divisors to establish the primality of the provided integer.

Example:
Input: 11
Output:
Prime

Prime Number

Consider the number 11. It is a prime number because the only ways to express it as a product involve 1 and 11. In other words, 11 cannot be obtained by multiplying any other pair of smaller natural numbers.

Now, let’s take the number 12. It is a composite number because it can be expressed as the product of 2 and 6 (2 × 6) or 3 and 4 (3 × 4). Unlike the prime number 11, 12 has multiple pairs of smaller natural numbers that can be multiplied to obtain it, making it a composite number.

  1. If a number has more than two factors, it is not a prime number.
  2. If a number has only two factors, namely 1 and itself, then it is considered a prime number.
  3. A prime number is divisible only by 1 and the number itself.
C

Method 1 :

#include <stdio.h>

int main() {
    int n = 11;
    int count = 0;

    if (n < 2) {
        printf("It's not prime\n");
    } else {
        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                count++;
            }
        }

        if (count > 2) {
            printf("It's not prime\n");
        } else {
            printf("It's prime\n");
        }
    }

    return 0;
}

Output :

It's prime
C++

Method 1 :

#include <iostream>

int main() {
    int n = 11;
    int count = 0;

    if (n < 2) {
        std::cout << "It's not prime" << std::endl;
    } else {
        for (int i = 1; i <= n; i++) {
            if (n % i == 0) {
                count++;
            }
        }

        if (count > 2) {
            std::cout << "It's not prime" << std::endl;
        } else {
            std::cout << "It's prime" << std::endl;
        }
    }

    return 0;
}

Output :

It's prime
JAVA

Method 1 :

public class Main {
    public static void main(String[] args) {
        int n = 11;
        int count = 0;

        if (n < 2) {
            System.out.println("It's not prime");
        } else {
            for (int i = 1; i <= n; i++) {
                if (n % i == 0) {
                    count++;
                }
            }

            if (count > 2) {
                System.out.println("It's not prime");
            } else {
                System.out.println("It's prime");
            }
        }
    }
}

Output :

It's prime
Python

Method 1 :

n = 11
count = 0

if n < 2:
    print("It's not prime")
else:
    for i in range(1, n + 1):
        if n % i == 0:
            count += 1

    if count > 2:
        print("It's not prime")
    else:
        print("It's prime")

Output :

It's prime