Header Ads

Header ADS

Prime number

 You can easily findout prime number by this code. You just have to give the range and nothing else.

here is the code:

while True:
    # Get range from user
    start = int(input("Enter the starting number: "))
    end = int(input("Enter the ending number: "))

    # Create an empty list to store prime numbers
    prime_nums = []

    # Iterate through the range of numbers
    for num in range(start, end+1):
        # Check if the number is prime
        if num > 1:
            for i in range(2, num):
                if (num % i) == 0:
                    break
            else:
                prime_nums.append(num)

    # Print out the prime numbers
    print("Prime numbers in the range: ", prime_nums)
    if input("Do you want to continue? (y/n)") == "n":
        break

the result



Working process

This code uses a while loop to repeatedly prompt the user for a starting and ending number. The user inputs are stored in the variables start and end. Then, an empty list prime_nums is created to store the prime numbers that are found within the given range. The code then uses a nested for loop to iterate through the range of numbers from start to end. For each number, the code checks if it is greater than 1, and if so, it uses another nested for loop to iterate through the range of numbers from 2 to the current number being checked. Within the inner loop, the code checks if the current number being checked is divisible by the current number in the inner loop. If it is divisible, the inner loop breaks, and the code moves on to the next number in the outer loop. If the inner loop completes without finding a divisor, it means the current number is prime, and it is added to the prime_nums list. After all the numbers in the range have been checked, the code prints out the prime_nums list, which contains all the prime numbers that were found. The code then prompts the user to continue or not, if the user entered 'n' the code will stop otherwise it will start again from the beginning and prompt the user for a new range of numbers to check.

No comments

Powered by Blogger.