

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

Our previous algorithm does this task and appends all the prime numbers to the ArrayList. What we have to do is print all the prime numbers between the range. We’ve declared two variables lower and upper and assigning those variables with user input. In the above code, we are initializing a scanner for reading user input. Let’s build the code now! Scanner sc=new Scanner(System.in) 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. After running the prime number algorithm for each number we are pushing it into ArrayList if it is a prime number. 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. In the above code, we’ve declared an ArrayList that stores all the prime numbers in the range of 1 to 100. Here’s the code to do that.Ĭheck out upGrad’s Java Bootcamp int n = 5 If the count is 2 then we can conclude that the given number is a prime, else it is not a prime. 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. Anything 8 or higher will simply duplicate the work we've already done.Before jumping to the code, we’ll understand the algorithm to check if a number is a prime number or not. Once we calculate all the multiples through 7 we can be sure that we've generated all of the multiples. Then in our inner loop we will produce range(6, 50, 3) which will add 6, 9, 12, 15, etc to our noprimes set.Īs you can see, this simply generates multiples. The next time through we generate the number 3. Each of these numbers will be added to our noprimes set. This produces: 4, 6, 8, 10, etc until we hit 50. Then we iterate through the inner loop using 2 to produce this range: range(4, 50, 2). Hopefully that isn't too complicated! As an example, the first time we iterate through the outer loop, we generate the number 2. During each iteration we will use the number to iterate through the range 2i through 50 with an interval of i. In this example we are using set comprehension to iterate through the numbers 2 through 7.

The function range(2, 8) will generate the numbers 2-7. We are using a set in this case because we only want to include each multiple once. noprimes = set(j for i in range(2, 8) for j in range(i*2, 50, i)) Therefore, if we want to generate a list of non-primes under 50 we can do so by generating multiples. A prime number is one that is only divisible by 1 and itself. To begin, we need to think about what a prime number is. Generating a list of non-primes is much simpler than generating a list of primes.
