Even numbers are those divisible by 2, like 2, 4, 6, 8, etc.
Odd numbers are those that are not divisible by 2, like 1, 3, 5, 7, etc.
Prime numbers are those greater than 1 that are divisible only by 1 and themselves, like 2, 3, 5, 7, 11, etc.
Code Example:
def generate_numbers(n):
even_numbers = []
odd_numbers = []
prime_numbers = []
for num in range(1, n + 1):
# Check if number is even or odd
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
# Check if number is prime
if num > 1:
is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
prime_numbers.append(num)
return even_numbers, odd_numbers, prime_numbers
# Example usage
n = 20
evens, odds, primes = generate_numbers(n)
print("Even numbers:", evens)
print("Odd numbers:", odds)
print("Prime numbers:", primes)
What the code does:
For even numbers, it checks if the number is divisible by 2 (num % 2 == 0).
For odd numbers, it adds those numbers that are not divisible by 2.
For prime numbers, it checks if a number is divisible by any number other than 1 and itself. It only checks up to the square root of the number for efficiency.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Explanation
Even numbers are those divisible by 2, like 2, 4, 6, 8, etc.
Odd numbers are those that are not divisible by 2, like 1, 3, 5, 7, etc.
Prime numbers are those greater than 1 that are divisible only by 1 and themselves, like 2, 3, 5, 7, 11, etc.
Code Example:
What the code does:
For even numbers, it checks if the number is divisible by 2 (
num % 2 == 0).For odd numbers, it adds those numbers that are not divisible by 2.
For prime numbers, it checks if a number is divisible by any number other than 1 and itself. It only checks up to the square root of the number for efficiency.
Output for
n = 20:Even numbers: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Odd numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
Prime numbers: [2, 3, 5, 7, 11, 13, 17, 19]
This code provides a simple way to categorize numbers as even, odd, and prime up to a given number
n.