Function to check if the number is even or odd
时间: 2024-02-13 14:06:05 浏览: 99
Sure! Here's a Python function to check if a number is even or odd:
```
def is_even(num):
if num % 2 == 0:
return True
else:
return False
```
You can call this function with any integer value as an argument, and it will return `True` if the number is even and `False` if it's odd. For example:
```
>>> is_even(4)
True
>>> is_even(7)
False
```
相关问题
Write a C function named isPrime that checks whether a given number is a prime or not. Include the fuction isPrime in a working program to verify Goldbach's Conjecture: Every even number greater than 4 can be written as the sum of two odd prime numbers. Make sure the function isPrime is called from the main method, and correctly returns a value to the main method.
Sure, here is a C program that includes the `isPrime` function to verify Goldbach's Conjecture:
```
#include <stdio.h>
int isPrime(int num);
int main() {
int num, i, j;
printf("Enter an even number greater than 4: ");
scanf("%d", &num);
if (num <= 4 || num % 2 != 0) {
printf("Invalid input!\n");
return 0;
}
for (i = 3; i <= num / 2; i += 2) {
if (isPrime(i) && isPrime(num - i)) {
printf("%d = %d + %d\n", num, i, num - i);
}
}
return 0;
}
int isPrime(int num) {
int i;
if (num < 2) {
return 0;
}
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
```
The `isPrime` function takes an integer as input and returns 1 if the number is prime, and 0 otherwise. The `main` function prompts the user to enter an even number greater than 4, and then checks whether the input is valid. If the input is valid, the program uses a for loop to check all odd prime numbers less than or equal to half of the input number. For each odd prime number `i`, the program checks whether the difference between the input number and `i` is also a prime number. If both numbers are prime, the program prints out the input number as the sum of `i` and the difference between the input number and `i`. If no such pairs of prime numbers are found, the program prints nothing. The `isPrime` function is called from the `main` function to check whether each number is prime.
编写一个名为collatz()的函数,它有一个名为number的参数。如果参数是偶数,那么collatz()就输出number//2,并返回该值。如果number是奇数,collatz就输出并返回3*number+1。
当然可以,这是一个简单的函数设计,使用了所谓的Collatz猜想,也称为3x+1序列。你可以按照以下方式编写这个Python函数:
```python
def collatz(number):
"""
This function takes an integer 'number' as input and follows the Collatz sequence rules.
If the number is even, it divides by 2 (number // 2).
If the number is odd, it multiplies by 3 and adds 1 (3 * number + 1).
:param number: An integer to start the Collatz sequence.
:return: The next number in the Collatz sequence.
"""
if number % 2 == 0: # Check if number is even
return number // 2
else:
return 3 * number + 1
# Test the function with some values
print(collatz(5)) # Output: 16
print(collatz(10)) # Output: 5
```
在这个函数中,我们首先检查输入数字是否是偶数,如果是,则除以2;如果不是,乘以3加1。然后返回新的结果,这个过程一直持续到数字变为1为止,因为所有奇数都会按照这个规律最终变成1。
阅读全文