Prime Number From 1 to 100 Program in Java

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.

Java Program to display prime numbers from 1 to 100

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 numberToCheckis prime, we return true.
  • In the main method, check isPrime is TRUE and add to primeNumbersFound String
  • Lastly, print the results
    1. public class primeNumbersFoundber {
    2.  
    3. public static void main(String[] args) {
    4.  
    5. int i;
    6. int num = 0;
    7. int maxCheck = 100; // maxCheck limit till which you want to find prime numbers
    8. boolean isPrime = true;
    9.  
    10. //Empty String
    11. String primeNumbersFound = "";
    12.  
    13. //Start loop 1 to maxCheck
    14. for (i = 1; i <= maxCheck; i++) {
    15. isPrime = CheckPrime(i);
    16. if (isPrime) {
    17. primeNumbersFound = primeNumbersFound + i + " ";
    18. }
    19. }
    20. System.out.println("Prime numbers from 1 to " + maxCheck + " are:");
    21. // Print prime numbers from 1 to maxCheck
    22. System.out.println(primeNumbersFound);
    23. }
    24. public static boolean CheckPrime(int numberToCheck) {
    25. int remainder;
    26. for (int i = 2; i <= numberToCheck / 2; i++) {
    27. remainder = numberToCheck % i;
    28. //if remainder is 0 than numberToCheckber is not prime and break loop. Elese continue loop
    29. if (remainder == 0) {
    30. return false;
    31. }
    32. }
    33. return true;
    34. }
    35. }

    Output:

    Prime numbers from 1 to 100 are:
    2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 

No comments:

Post a Comment