Python program to check a number n is weird or not

A number is considered weird based on specific conditions involving whether it's odd or even and its range. Understanding these conditions helps us write a program to classify any given number.

Weird Number Conditions

A number n is weird when ?

  • The number is odd
  • The number is not in range 2 to 5
  • The number is even and in range 6 to 20

So, if the input is n = 18, then the output will be "Weird" because it is even and in range 6 to 20.

Algorithm

To solve this, we follow these steps ?

  • If n is odd, then return "Weird"
  • Otherwise when (n > 1 and n < 6) or n > 20, then return "Not Weird"
  • Otherwise when n >= 6 and n <= 20, then return "Weird"

Example

Let us see the following implementation to get better understanding ?

def solve(n):
    if n & 1:  # Check if odd using bitwise AND
        return "Weird"
    elif (n > 1 and n < 6) or n > 20:
        return "Not Weird"
    elif n >= 6 and n <= 20:
        return "Weird"

# Test with different numbers
test_numbers = [1, 3, 4, 7, 18, 22]

for n in test_numbers:
    result = solve(n)
    print(f"n = {n}: {result}")

The output of the above code is ?

n = 1: Weird
n = 3: Weird
n = 4: Not Weird
n = 7: Weird
n = 18: Weird
n = 22: Not Weird

How It Works

The function uses bitwise AND operator (n & 1) to check if a number is odd. When a number is ANDed with 1, the result is 1 if the number is odd, and 0 if even. The conditions are checked in sequence to determine if the number falls into the "weird" category.

Conclusion

This program efficiently classifies numbers as weird or not weird based on the given conditions. The bitwise operation makes the odd/even check more efficient than using the modulo operator.

Updated on: 2026-03-26T14:25:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements