Python

How to write a program that displays all prime numbers between 1 and 100

Here is a simple program in Python that displays all prime numbers between 1 and 100:

This program uses a nested loop to check if a number is prime. The outer loop iterates over the numbers between 2 and 100, and the inner loop checks if the current number is divisible by any number between 2 and itself. If the number is not divisible by any of these numbers, it is a prime number and it is printed to the screen.




The break statement is used to exit the inner loop if the number is divisible by a number between 2 and itself. The else clause of the outer loop is executed if the break statement is not reached, which means that the number is prime.

This program will output the following list of prime numbers:


Here is an alternative solution that uses a different algorithm to check if a number is prime:

This program defines a function is_prime that takes a number n as an argument and returns True if it is prime, and False otherwise. The function first checks if the number is 2 or 3, which are both prime. It then checks if the number is 1 or divisible by 2, in which case it returns False.

If the number is not 1 or divisible by 2, the function iterates over the odd numbers between 3 and the square root of the number, and checks if the number is divisible by any of these numbers. If the number is not divisible by any of these numbers, it is a prime number and the function returns True.

The main loop iterates over the numbers between 1 and 100, and uses the is_prime function to check if each number is prime. If a number is prime, it is printed to the screen.

This program will output the same list of prime numbers as the previous solution.


Here is another alternative solution that uses the Sieve of Eratosthenes algorithm to find all prime numbers between 1 and 100:

This program defines a function sieve that takes a number n as an argument and returns a list of all prime numbers between 1 and n.

The function initializes a list sieve of True values up to n, and an empty list primes to store the prime numbers. It then iterates over the numbers between 2 and n, and checks if the current number is marked as True in the sieve list. If it is, it is a prime number and it is added to the primes list. The function then marks all multiples of the current number as False in the sieve list, so that they are not considered as prime numbers in the future.

Finally, the function returns the primes list.

The main loop calls the sieve function with an argument of 100, and prints the returned list of prime numbers.

This program will output the same list of prime numbers as the previous solutions.

Leave a Comment