Prime Number - Hackerearth Problem Solution - CODELABS3277

So with the hope that you have tried to solve this problem, if not then please give it a try before seeing the solutions.

If already tried then here we will be exploring numerous ways to solve this problem. Though it is a very basic problem from Basic Programming Section!


Given: Positive Integer, N and we need to display all the prime number till N.
it is also given that 1<=N<=1000,

Solution 1:

So the concept which is used to solve is that every prime number has to factor 1 and itself. So run a loop from 1 to n and count the factors, if it is 2 then prime else not.


By - PraveenKumarRana

Solution 2:

In this, we are dividing each number(i in this case) with j(2<=j<i). if i gets divisible by j then we do not need  to check with other j as it failed to be a prime number and thus inner loop breaks.
If it does not enter if condition then flag remains 0 which means it is not divisible by any j so it's a prime number .
 

By - Amar Kumar

If you find any error in explanation or in code, do write in the comment section.  These are the codes which we have written and submitted in Hackerearth.

Thank You
Happy Coding
Enjoy!

Comments