Python program to print prime numbers from 1 to n

Prime number

A prime number is an integer greater than 1 whose only factors are 1 and itself. A factor is an integer that can be divided evenly into another number.

Logic

To print all the prime numbers up to N, we start one loop from 2 to N and then inside the loop we check current number or “num” is prime or not. To check if it is prime or not we again need one nested loop. It is not an efficient way to check prime number but it is simpler to understand the basic of looping in Python.

See also: Check whether a number is prime number or not

Program

# Take input from user
upto = int[input["Find prime numbers upto : "]]

print["\nAll prime numbers upto", upto, "are : "]

for num in range[2, upto + 1]:

    i = 2

    for i in range[2, num]:
        if[num % i == 0]:
            i = num
            break;

    # If the number is prime then print it.
    if[i != num]:
        print[num, end=" "]

Output

Find prime numbers upto : 100
All prime numbers upto 100 are :
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given a number N, the task is to print the prime numbers from 1 to N.
    Examples: 

    Input: N = 10
    Output: 2, 3, 5, 7
    
    Input: N = 5
    Output: 2, 3, 5 

    Algorithm:  

    • First, take the number N as input.
    • Then use a for loop to iterate the numbers from 1 to N
    • Then check for each number to be a prime number. If it is a prime number, print it.

    Approach 1:  Now, according to formal definition, a number ‘n’ is prime if it is not divisible by any number other than 1 and n. In other words a number is prime if it is not divisible by any number from 2 to n-1.

    Below is the implementation of the above approach:  

    C++

    #include

    using namespace std;

    bool isPrime[int n]

    {

        if [n == 1 || n == 0]

            return false;

        for [int i = 2; i < n; i++] {

            if [n % i == 0]

                return false;

        }

        return true;

    }

    int main[]

    {

        int N = 100;

        for [int i = 1; i

    Chủ Đề