Python Program to Find Prime Numbers from 1 to 100

please click here for more wordpress cource

Here’s a Python program to find prime numbers from 1 to 100:

# function to check if a number is prime
def is_prime(n):
    # corner cases
    if n <= 1:
        return False
    if n <= 3:
        return True

    # check if number is divisible by 2 or 3
    if n % 2 == 0 or n % 3 == 0:
        return False

    # check for divisibility by all numbers greater than 3 and less than or equal to the square root of n
    i = 5
    while i * i <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6

    return True

# loop through numbers from 1 to 100 and print prime numbers
for num in range(1, 101):
    if is_prime(num):
        print(num, end=" ")

Output:

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

This program uses a function is_prime() to check if a given number is prime or not. It then loops through numbers from 1 to 100 and prints the prime numbers. The is_prime() function uses a basic algorithm that checks for divisibility by numbers greater than 3 and less than or equal to the square root of the number being checked.

You may also like...

Popular Posts

Leave a Reply

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