Write a function, is_prime, that takes a single integer argument and returns True when the argument is a prime number and False otherwise.
时间: 2024-05-08 19:18:04 浏览: 194
Sure, here's the code for the is_prime function in Python:
```
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
```
This function checks if the input integer is greater than 1 (since 1 is not a prime number), and then iterates through all integers from 2 to the square root of the input integer. If any of these integers divide the input integer evenly, then it's not a prime and the function returns False. Otherwise, the input integer is a prime and the function returns True.
相关问题
: Write a Python function named "is_even" that takes an integer as input and returns True if the number is even, and False otherwise
Sure! Here's the Python code for the `is_even` function that takes an integer as input and returns `True` if the number is even, and `False` otherwise:
```python
def is_even(num):
if num % 2 == 0:
return True
else:
return False
```
You can call this function by passing an integer as an argument like this:
```python
print(is_even(4)) # Output: True
print(is_even(5)) # Output: False
```
In the first call to the function, the input `4` is an even number, so the function returns `True`. In the second call to the function, the input `5` is an odd number, so the function returns `False`.
Write a C program that inputs a series of integers and passes them one at a time to function even, which uses the modulus operator to determine whether an integer is even. The function should take an integer argument and return true if the integer is even and false otherwise.
Sure, here's a C program that inputs a series of integers and passes them one at a time to function even, which uses the modulus operator to determine whether an integer is even. The function takes an integer argument and returns true if the integer is even and false otherwise:
```c
#include <stdio.h>
#include <stdbool.h>
bool even(int num);
int main() {
int num;
printf("Enter a series of integers (enter 0 to stop):\n");
do {
scanf("%d", &num);
if (even(num)) {
printf("%d is even.\n", num);
}
else {
printf("%d is odd.\n", num);
}
} while (num != 0);
return 0;
}
bool even(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
```
In this program, the main function first prompts the user to enter a series of integers. It then uses a do-while loop to repeatedly read in integers using scanf(), and pass them to the even function. The even function uses the modulus operator to determine whether the integer is even, and returns true if it is and false otherwise. Finally, the main function prints out whether each integer is even or odd using printf().
阅读全文