use C program A prime number is called a Mersenne prime if it can be written in the form - 1 for some positive integer p. Write a program that finds how many Mersenne primes less than or equal to the number n you input.
时间: 2024-02-14 07:06:39 浏览: 29
Sure, here's a C program that finds the number of Mersenne primes less than or equal to a given number n:
```
#include <stdio.h>
#include <math.h>
int is_prime(int num) {
int i;
if (num == 2) {
return 1;
}
if (num % 2 == 0 || num == 1) {
return 0;
}
for (i = 3; i <= sqrt(num); i += 2) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int n, i, count = 0;
printf("Enter a number: ");
scanf("%d", &n);
for (i = 2; i <= n; i++) {
if (is_prime(i) && is_prime(pow(2, i) - 1)) {
count++;
}
}
printf("There are %d Mersenne primes less than or equal to %d.\n", count, n);
return 0;
}
```
The program works by iterating through all numbers from 2 to n, and checking whether each number is a Mersenne prime. To check whether a number is a Mersenne prime, we first check whether the exponent is prime (using the `is_prime` function), and then check whether 2^p-1 is also prime. If both conditions are true, then the number is a Mersenne prime and we increment the count. Finally, we print out the total count of Mersenne primes less than or equal to n.
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)