How to Print Prime Numbers from 1 to 100 in Java [Solved]

Hello guys, today, I'll share with you a simple problem of writing a Java program to print prime numbers up to a given number like saying prime numbers from 1 to 100. It's one of the most common coding exercises for programmers learning in Java, as it gives you an opportunity to learn more about the essential operators in Java Programming. The key here is that you cannot use a library function which can simplify your job, you need to devise the algorithm for checking prime number by yourself. One of the most popular algorithms for generating prime is Sieve of Eratosthenes,  which we have discussed earlier, but in this post, we will take a simpler approach.

We'll first write a function to check whether a number is prime or not and then we loop through the first 100 numbers i.e. from 1 to 100 and print only those which passed the prime test.

Btw, if you are looking for some serious programming coding questions for the interview, then you can also take a look at Cracking the coding interview book by Gayle Mcdowell which contains more than 150 coding questions with solutions.

And, if you are serious about improving your coding skills and cracking tough coding interviews from FAANG companies like Facebook, Google, Apple, Amazon, etc then you can also checkout Grokking the Coding Interview: Patterns for Coding Questions, an interactive course from Educative. 

This course will teach you 15 essential coding patterns like sliding window, merge interval, fast and slow pointers, etc which can be used to solve 100+ Leetcode problems. Knowing these patterns and how to apply them will certainly boost your chances in real coding interviews. 




How to check if a number is prime or not in Java? Solution

A number is said to be prime if it's not divisible by any number other than itself like 2, 3, or 5. 1 is not counted as a prime number, so the lowest prime number is 2. One of the easiest ways to check whether a number is prime or not is to loop from 2 to the number itself and checks if it's divisible by any number in between or not.

You can do that check by using a modulus operator in Java, which returns zero if a number is perfectly divisible by another number. If the number you are checking is not divisible by anyone then it's a prime number otherwise, it's not a prime number.

But this logic can be further optimized to only loop through the square root of the number instead of the number itself, as shown in the below example. This will make the Java program fast for checking large prime numbers.

Here is a list of all prime numbers between 1 and 100:

Java Program to print prime numbers from 1 to 100


An optimized way to generate Prime numbers from 1 to 100

And, here is our complete Java program which shows an optimized way to generate prime numbers in the range of 1 to 100. 
/**
 * Java Program to print prime numbers from 1 to 100
 *
 * @author Javin Paul
 */
public class PrimeNumberGenerator {

    public static void main(String args[]) {

        // print prime numbers from 1 - 100
        System.out.println("Prime numbers from 1 to 100 ");

        for (int i = 2; i <= 100; i++) {
            if (isPrime(i)) {
                System.out.println(i);
            }
        }
    }

    /*
     * An optimized to check if a number is prime or not.
     */
    public static boolean isPrime(int num) {
        if (num == 2 || num == 3) {
            return true;
        }

        if (num % 2 == 0 || num % 3 == 0) {
            return false;
        }

        for (int i = 3; i < Math.sqrt(num); i += 2) {
            if (num % i == 0 || num % Math.sqrt(num) == 0) {
                return false;
            }
        }
        return true;

    }
}

Output:
Prime numbers from 1 to 100 
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

That's all about how to print prime numbers in Java from 1 to 100.  Let me know if you find any bug in this program or you think if this program will not work in any specific scenario. This looks much more optimized than looping to the number itself. You can use this technique to solve other coding problems which are based on prime numbers. Knowing this trick is really useful for competitive programming as well. 


Here are a couple of more coding problems for practice:
  • Top 10 Programming problems from Java Interviews? (article)
  • Write a program to code insertion sort algorithm in Java (program)
  • How to find a missing number in a sorted array? (solution)
  • Write a program to check if a number is a power of two or not? (solution)
  • How to calculate factorial using recursion and iteration? (solution)
  • How do you reverse the word of a sentence in Java? (solution)
  • How to find duplicate characters from String in Java? (solution)
  • How to reverse an integer variable in Java? (solution)
  • Write code to implement the Quicksort algorithm in Java? (algorithm)
  • How to reverse String in Java without using StringBuffer? (solution)
  • How to check if a year is a leap year in Java? (answer)
  • Write code to implement a Bubble sort algorithm in Java? (code)
  • How to print the Pyramid pattern in Java? (solution)
  • How to check if a given number is prime or not? (solution)
  • How do you swap two integers without using a temporary variable? (solution)
  • How to solve the FizzBuzz problem in Java? (solution)
  • Write a program to print the highest frequency word from a text file? (solution)
  • How to remove duplicate elements from ArrayList in Java? (solution)
  • How to find if given String is a palindrome in Java? (solution)
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or doubt then please let us know and I'll try to find an answer for you. As always suggestions, comments, innovative and better answers are most welcome.

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check the Data Structure in Java free course on Udemy. It's completely free and all you need to do is create a free Udemy account to enroll in this course. 

18 comments:

  1. the new blog looks really good. Thanks.

    ReplyDelete
  2. Another interesting read. But there is a bug in the code. When testing n for prime, the logic should check reminder from 3 up to (and including) square root of n. That is why 25 and 49 are showing up as "prime" in your output.

    ReplyDelete
  3. if (num % i == 0 || num % Math.sqrt(num) == 0)

    ReplyDelete
  4. @Clarence and @Marverick, Good catch, thanks

    ReplyDelete
  5. 'isPrimeOrNot' is a terrible name for a function... 'isPrime' describes way better what the function does. Also, you must have some other bug lying around because your result also contains 9 which is not prime...

    ReplyDelete
    Replies
    1. @Leandro, agree, changed to isPrime(), make more sense. Regarding 9, you are correct, 9 is not a prime number, corrected the logic.

      Delete
  6. You've written that 2 is a prime number then why there is no 2 in output result?

    ReplyDelete
    Replies
    1. @Alekesy, Good spotting, corrected it now. Thanks

      Delete
  7. Neat code. I would like to suggest an improvement
    At this piece of code
    for (int i = 3; i < Math.sqrt(num); i += 2)
    {
    if (num % i == 0 || num % Math.sqrt(num) == 0) {
    return false;
    }
    With a slight change the or (||) statement could be omitted. The counter 'i' could be also checked for equality to the square root of num. Hence i <= Math.sqrt(num).

    ReplyDelete
  8. Shouldn't we cache Math.sqrt value?

    ReplyDelete
    Replies
    1. @Anonymous, calculating square is not as costly as calculating factorial or fibonacci numbers, but yes, for improved performance you can surely cache.

      Delete
  9. Replies
    1. Thank you @Somesh, please share your friends, it does help a lot.

      Delete
  10. Hi Javin. Firstly, thanks for your good articles. I'm your new subscriber.
    I wondered why didn't use num%Math.sqrt(num) in first if condition. Because num not changes. If we use like this, it can reduce complexity of algorithm and in some situation maybe increase efficiency. Again thank you so much. Good work.


    if (num % 2 == 0 || num % 3 == 0 || Math.sqrt(num)) {
    return false;
    }
    for (int i = 3; i < Math.sqrt(num); i += 2) {
    if (num % i == 0) {
    return false;
    }
    }


    ReplyDelete
  11. I really like your blog, but I can't tell you how frustrating it is not being able to simply copy and paste the examples into eclipse and simply run them ... do you do that on purpose? just curious

    ReplyDelete
  12. but why it doesnt show the ms that takes to print

    ReplyDelete
  13. obv bad code. dividing number by all up to sqrt(n)
    math is: any number is multiplication of prime numbers!

    thus , just keep generated primes, and try to divide to test each number by primes generated before!

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.