Prime Detector

From Esolang
Jump to navigation Jump to search

Prime Detector is a very classic programming challenge. Any programming language capable of completing this challenge will be proven to have the following characteristics:

  • I/O
  • Simple arithmetic operations
  • Conditional jump
  • Iterative loops or conditional loops
  • Advanced arithmetic operations (such as square roots)

The challenge requires writing a program that takes an input, determines whether it is a prime number, and then outputs the result.

Challenge Zone

Python

def is_prime(n):
    """Check if a number is prime."""
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    
    # Check only odd divisors up to sqrt(n)
    for i in range(3, int(n**0.5) + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    try:
        # Get user input
        num = int(input("Enter a number: "))
        
        # Check if prime
        if is_prime(num):
            print(f"{num} is a prime number.")
        else:
            print(f"{num} is not a prime number.")
            
    except ValueError:
        print("Please enter a valid integer.")

if __name__ == "__main__":
    main()

See Also

Categories