Programs

Prime Numbers From 1 To 100 in Java: Display 1 to 100 in Java

Introduction

First of all, let’s get started with the prime number definition. A number is said to be a prime number if it is divisible by only 1 and itself. If we were asked to say prime numbers from 1 to 100 then it would be a tedious task to check each number on paper and say whether it is a prime number or not. Never mind we can write a code to do that and java makes things easy.

A Prime Number is a natural number greater than 1 and not a product of two smaller natural numbers. For example, 13 is only divisible by one or itself. The list of 1 to 100 prime numbers in Java is 2, 3, 5, 7, 11, 13, 17, and so on.

Note: 0 and 1 are not prime numbers; 2 is the only even prime number.

Java is a popular and one of the most used languages, and the reason for its sunny day spotlight is providing features like object-oriented programming, platform independency, predefined libraries, etc.

Let’s build a code for printing prime numbers from 1 to 100 and walk through it. Let’s start!

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

Java Program

Before jumping to the code, we’ll understand the algorithm to check if a number is a prime number or not. At first, we need to loop over all the numbers from 1 to N and maintain a count of numbers that properly divides the given number. If the count is 2 then we can conclude that the given number is a prime, else it is not a prime. Here’s the code to do that.

Check out upGrad’s Java Bootcamp

int n = 5;
int c = 0;
for(int i=1;i<=n;i++)
  if(n%i==0)
      c++;
if(c==2)
    System.out.println(n+” is a prime number”);
else
    System.out.println(n+” is not a prime number”);

In the above snippet n is the number which is to be checked if it is a prime number or not, c is a variable that stores the count of proper divisors. And we are looping over the range 1 to n and incrementing the count if we found a proper divisor.

And after coming out of the loop, we are checking if the count is 2 i.e.; there are only two proper divisors (1 and itself). If yes concluding it as a prime number, else a non-prime number. Talking about the time complexity of the above code it is a linear one, so it’s an O(n) complexity code.

Now that we were asked to print prime numbers from 1 to 100, we need to run this same algorithm for each number between 1 to 100 and store the prime number. And here’s the code to do that.

Check out upGrad’s Advanced Certification in DevOps

ArrayList<Integer> a=new ArrayList<>();
  for(int n=1; n<=100; n++){
  int c = 0;
  for (int i = 1; i <= n; i++)
      if (n % i == 0)
          c++;
  if (c == 2)
      a.add(n);
  else
      continue;
  }
  System.out.println(a);

In the above code, we’ve declared an ArrayList that stores all the prime numbers in the range of 1 to 100. Now we have two for loops first for loop is for looping over all the numbers between 1 to 100 and the second for loop is our previous prime number algorithm. After running the prime number algorithm for each number we are pushing it into ArrayList if it is a prime number.

In-Demand Software Development Skills

Check out: Java Developer Salary in India

And after completing the loops we are printing our ArrayList which displays all the prime numbers between 1 to 100. Talking about the time complexity of the above code, we can see that there are two for loops. So it is an O(n²) complexity code.

We have hardcoded the range in the above code, what if we want to print prime numbers in the range given by the user input?

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Prime Numbers in Given Input Range

The whole algorithm will be almost similar to the above code, the only difference we make is taking user input for the lower limit and upper limit of the range.

Let’s build the code now!

Scanner sc=new Scanner(System.in);
int lower=sc.nextInt();
int upper=sc.nextInt();
ArrayList<Integer> a=new ArrayList<>();
for(int n=lower; n<=upper; n++){
int c = 0;
for (int i = 1; i <= n; i++)
if (n % i == 0)
c++;
if (c == 2)
a.add(n);
else
continue;
}
System.out.println(a);

In the above code, we are initializing a scanner for reading user input. We’ve declared two variables lower and upper and assigning those variables with user input. What we have to do is print all the prime numbers between the range [lower, upper]. Our previous algorithm does this task and appends all the prime numbers to the ArrayList.

Also Read: Java Project Ideas & Topics

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

The following section explains how to find prime number between 1 to 100 in Java.

Program Logic:

The key method of the prime number program in Java includes a loop to check and find prime number between 1 to 100 in Java.

The main method calls the method “CheckPrime” to decide whether a number is prime or not in Java. For example, we have to divide an input number, say 15, from values 2 to 15 and check the remainder. But if the remainder is 0, the number is not prime.

Note that no number is divisible by more than half of itself. Hence, we must loop through just numToCheck/2. So, if the input is 15, its half is 7.5, and the loop will repeat through values 2 to 8.

If numToCheck is completely divisible by another number, the output is false, and the loop is broken.

But if numToCheck is prime, the output is true.

In the main method for how to find prime numbers from 1 to 100 in Java, check isPrime is TRUE and add it to primeNumFound String.

Here is the Java program to print prime numbers from 1 to 100.

public class primeNumFoundber {

    public static void main(String[] args) {

        int i;

        int num = 0;

        int maxCheck = 100; // The limit to find prime numbers is up to 100

        boolean isPrime = true;

        //Empty String

        String primeNumFound = “”;

        //Start loop#2 to maxCheck

        for (i = 2; i <= maxCheck; i++) {

            isPrime = CheckPrime(i);

            if (isPrime) {

             primeNumFound = primeNumFound + i + ” “;

            }

        }

        System.out.println(“Prime numbers from 1 to ” + maxCheck + “:”);

        // It prints prime numbers from 1 to maxCheck

    System.out.println(primeNumFound);

}

    public static boolean CheckPrime(int numToCheck) {

        int remainder;

        for (int i = 2; i <= numToCheck / 2; i++) {

            remainder = numToCheck % i;

            //if remainder gives 0 than numToCheckber is not prime number and breaks loop, else it continues the loop

         if (remainder == 0) {

             return false;

            }

        }

        return true;

}

}

Output:

The output of this Java program to print prime numbers from 1 to 100 would be:

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

Find Prime Number using While Loop in Java

  1. In this program of calculating prime no between 1 to 100 in Java, the while loop is available in the constructor. If we instantiate the class, the constructor will be automatically executed.
  2. Read the “n” value through scanner class object sc.Int(). “FindoutPrime class” is introduced in the class Prime as a new FindPrime(n); the constructor of “FindoutPrime” will be performed.

The while loop in Java iterates until i<=num is false. The remainder of the number/i=0 count will be incremented by 1 and “i” value is increased by 1. If the count=2, the code prints, “number is a prime number”.

Find Prime Number using While Loop in Java:

The program to find prime no between 1 to 100 in Java using “While Loop” is as below.

import java.util.Scanner;

class FindoutPrime

{

         FindoutPrime (int num)

         {

         int count=0,i=1;

         while(i<=num)

         {

           if(num%i==0)

           {

             count++;     

           }

         i++;

         }

         if(count==2)

           System.out.println(num+” is a prime number “);

         else

         System.out.println(num+” is not a prime number “);   

         }

}

class Prime

{

         public static void main(String arg[])  

         {

               System.out.println(“Enter a number “);

         Scanner sc=new Scanner(System.in);

         int n=sc.Int();

         new FindoutPrime (n);

         }

}

Output:

The output of the above program on how to find prime numbers from 1 to 100 in Java:

Enter a number

83

83 is a prime number

Output

Enter a number

80

80 is not a prime number

Find Prime Number using Recursion in Java:

Here are the steps to find prime numbers between 1 to 100 in Java using Recursion.

  1. Firstly, read the entered number n.
  2. The Prime class object will be created in the main method. This step calls the method CheckPrimeOrNot (n) with the help of object p.CheckeprimeOrNot(n);

iii. The method CheckPrimeOrNot (int num) will run and call itself as CheckPrimeOrNot (num). It executes until the condition if(i<=num) is false. But if the condition is false, this method returns the count and is assigned to the c variable. If count=2, the code prints “prime number” else, it prints “not a prime number”.

import java.util.Scanner;

class Prime

{     

         static int count=0,i=1;

         int CheckPrimeOrNot (int num)

         {

                     if(i<=num)

                     {

                       if(num%i==0)

                       {

                         count++;           

                       }

                       i++;

                     CheckPrimeOrNot (num);

                     }

         return count;

         }

         public static void main(String arg[])  

         {

               System.out.println(“Enter a number “);

         Scanner sc=new Scanner(System.in);

         int n=sc.Int();

         Prime p=new Prime();

         int c=p. CheckPrimeOrNot (n);

         if(c==2)

           System.out.println(“prime number “);

         else

           System.out.println(“not a prime number “);   

         }

}

Output:

The  output of prime numbers between 1 to 100 in Java.

Enter a number

8

not a prime number

These are the various methods to find the given range of prime numbers 1 to 100 java. You can implement several programming methods to find, or print prime numbers 1 to 100 java.

Conclusion

We’ve understood the definition of prime numbers, walked through an algorithm to find whether a number is prime or not, extended that algorithm to find prime numbers from 1 to 100. And later we’ve used a java scanner to read user input for tweaking the range of numbers that are to be checked if they are prime or not, built an algorithm for printing prime numbers in a range given by the user.

Now that you are aware of how to check if a number is prime or not, how to print prime numbers in a given range. Try implementing few challenges like implementing it using functions, implementing it using objects, building the algorithm using recursion, try using few other collections in java, try optimizing the code a little bit if possible, etc. Because practice helps you in mastering a programming language, helps you in overcoming ambiguity with syntaxes and implementation.

If you wish to improve your Java skills, you need to get your hands on these java projects. If you’re interested to learn more about Java, full-stack development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

What are prime numbers?

Prime numbers are positive integers with exactly two distinct factors, 1 and themselves. Primes are what mathematicians call irreducibl and indivisible. Primes are the building blocks of our number system, like how the atoms are the building blocks of the world. The prime numbers are the numbers that are divisible only by one and by itself.

What is sieves of Eratosthenes?

The Sieve of Eratosthenes is an ancient Greek algorithm for finding the prime numbers. The algorithm is known for its simplicity and efficiency, in the sense that it is quite fast for its time and yet it yields prime numbers very well. The algorithm works by eliminating all the multiples of each prime from the composite numbers, starting from the multiples of 2 and ending in the multiples of N (N is the last number you want to find the primes for). Eratosthenes was a Greek mathematician and was considered to be the founder of the library of Alexandria in Egypt. He is well known for calculating the circumference of Earth and its diameter.

What are data structures and algorithms?

A data structure is a way for storing data so that a computer program can retrieve and modify it. A data structure is a programming language abstraction. It may be an entity in itself or a part of another data entity. It may be data in its own right, or it may be a mechanism for accessing and manipulating other data. A data structure consists of the data definition, data type, content and the operations that can be applied to the content. Algorithms are the step-by-step procedures for solving a computer problem. Each algorithm is a sequence of actions that will lead to a solution to the problem.

Want to share this article?

Become a Full Stack Developer

Leave a comment

Your email address will not be published. Required fields are marked *

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks