What is a Prime Number?
A prime number is a number that is only divisible by 1 or itself. For example, 11 is only divisible by 1 or itself. Other Prime numbers 2, 3, 5, 7, 11, 13, 17….
Note: 0 and 1 are not prime numbers. 2 is the only even prime number.
How to display prime numbers between 1 to 100 using Java Code
Program Logic:
- The main method contains a loop to check prime numbers one by one.
- The main method calls the method
CheckPrime
to determine whether a number is prime - We need to divide an input number, say 17 from values 2 to 17 and check the remainder. If the remainder is 0 number is not prime.
- No number is divisible by more than half of itself. So, we need to loop through just numberToCheck/2. If the input is 17, half is 8.5, and the loop will iterate through values 2 to 8
- If
numberToCheck
is entirely divisible by another number, we return false, and loop is broken. - If
numberToCheck
is prime, we return true. - In the main method, check isPrime is
TRUE
and add to primeNumbersFound String - Lastly, print the results