‹ All Computer Science notes
ISC Practicals and Theory - Prime Number
Updated 20 Oct 2026
A prime number is a number that has exactly two factors. This program accepts a number, counts its factors with a loop and tells whether it is prime, all inside main.
Definition
A natural number $N$ is a prime number if it has exactly two factors: $1$ and $N$ itself.
- $7$ is prime: its only factors are $1$ and $7$.
- $12$ is not prime: its factors are $1, 2, 3, 4, 6, 12$.
- $1$ is not prime: it has only one factor.
Algorithm
- Start. Read the number into
n. - If
n < 1, display "Invalid input" and stop. - Set
count = 0. - Repeat for
ifrom $1$ ton:- If
n % i == 0,iis a factor, so increasecountby $1$.
- If
- If
count == 2, display thatnis a prime number. Otherwise display that it is not. - Stop.
Program
The whole logic is written inside the main method of the class PrimeNumber.
import java.util.Scanner;
public class PrimeNumber
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n < 1)
{
System.out.println("Invalid input");
}
else
{
int count = 0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
count++;
}
if (count == 2)
System.out.println(n + " is a prime number");
else
System.out.println(n + " is not a prime number");
}
}
}Variable description table
| Variable | Data Type | Purpose |
|---|---|---|
| args | String[] | Command line arguments of main; not used |
| sc | Scanner | Object used to read the number typed by the user |
| n | int | Stores the number entered by the user |
| count | int | Counts the factors of n found so far |
| i | int | Loop counter; each value from 1 to n is tested as a factor |
Sample input and output
Sample 1
Enter a number: 7
7 is a prime numberSample 2
Enter a number: 12
12 is not a prime numberSample 3
Enter a number: 1
1 is not a prime numberSample 4
Enter a number: -4
Invalid inputDry run
Input: n = 7
| i | n % i | Factor? | count |
|---|---|---|---|
| 1 | 0 | Yes | 1 |
| 2 | 1 | No | 1 |
| 3 | 1 | No | 1 |
| 4 | 3 | No | 1 |
| 5 | 2 | No | 1 |
| 6 | 1 | No | 1 |
| 7 | 0 | Yes | 2 |
The loop ends with count = 2, so the program displays that $7$ is a prime number, as in the first sample run.
Variations
- Range: "Display all prime numbers between m and n."
- Twin primes: "Display all twin prime pairs in a given range."
- Emirp number: "Check whether a number is an emirp number: a prime whose reverse is also prime."