How to Represent Prime Numbers with a Bar of ‘X’ Characters in Python Coding?

Estimated read time 2 min read

To represent prime numbers with a bar of ‘X’ characters in Python, you can create a function that checks whether a number is prime, and then print a bar of ‘X’ characters for each prime number. Here’s an example:

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

def print_prime_bar(limit):
    for num in range(2, limit + 1):
        if is_prime(num):
            print('X' * num)

# Example usage
print_prime_bar(20)

In this example, the is_prime() function checks whether a number n is prime by iterating from 2 to the square root of n and checking for any divisors. If a divisor is found, the function returns False. Otherwise, it returns True.

The print_prime_bar() function takes a limit parameter that specifies the maximum number up to which prime numbers should be considered. It iterates from 2 to limit, and for each number that is prime, it prints a bar of ‘X’ characters with a length equal to the number itself.

In the example usage, print_prime_bar(20) prints the prime bars for prime numbers up to 20.

After running the script, you will see the bars of ‘X’ characters representing prime numbers. The length of each bar corresponds to the prime number itself.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply