#include <stdio.h>
int main(void) {
int n1 = 0, n2 = 1, n3, count, input_num;
printf("Please enter the number of terms: ");
scanf("%d", &input_num);
printf("%d\n%d\n", n1, n2);
for (count = 3; count <= input_num; count++) {
n3 = n1 + n2;
printf("%d\n", n3);
n1 = n2;
n2 = n3;
}
}
上面的代码输出的只是一个斐波那契数,但我想求斐波那契素数。如何在此代码中插入素数?
结果应该是这样的:
Please enter the number of terms: 6
Among the first 6 terms of Fibonacci series that are also prime: 2 3 5
创建一个函数,我们称它为
isPrime()
,过滤掉素数和非素数。
它的逻辑可能是这样的:
遍历所有大于 1(每个数字都可以被 1 整除)且小于或等于输入的平方根的数字,我们称之为
n
,并检查输入是否可以被这些数字整除,如果可整除则返回 false,否则返回 true。因为我们知道质数只能被 1 和它本身整除,所以这行得通。
这是它的样子:
#include <stdbool.h>
bool isPrime(int x) {
int n = /* Square root of x */;
if (/* x is less than or equal to 2 */) {
return true;
}
for (int i = 2; i <= n; i++) {
if (/* x is divisible by n */) {
return false;
}
}
return true;
}
您可以在您的原始代码中使用此功能:
printf("Among the first %d terms of the Fibonacci series that are also prime: ", input_num);
for (count = 3; count <= input_num; count++) {
n3 = n1 + n2;
if (isPrime(n3) == true) {
printf("%d ", n3);
}
n1 = n2;
n2 = n3;
}
printf("Please enter the number of terms: ");
scanf("%d", &input_num);
printf("%d\n%d\n", n1, n2);
for(count = 3; count <= input_num; count++){
n3 = n1 + n2;
for(int i=2; i<n3; i++){
if(n3%i==0){
printf("%d\n", n3);
}
}
n1 = n2;
n2 = n3;
我们初学者应该互相帮助。:)
对于初学者来说,数字 0 是第一个斐波那契数。那就是你需要从
0
开始计算斐波那契数。
这个for循环
for (count = 3; count <= input_num; count++) {
也应该从
0
开始。
使用的定义斐波那契数的变量应该有一个无符号整数类型,例如
unsigned int
.
要判断一个数是否是质数,最好写一个单独的函数。
这里有一个演示程序,展示了如何实现任务。
#include <stdio.h>
int is_prime( unsigned int n )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for (unsigned int i = 3; prime && i <= n / i; i += 2)
{
prime = n % i != 0;
}
return prime;
}
int main( void )
{
while (1)
{
printf( "Please enter the number of Fibonacci items (0 - exit): " );
unsigned int n;
if (scanf( "%u", &n ) != 1 || n == 0) break;
unsigned int fibonacci1 = 0;
unsigned int fibonacci2 = 1;
int present = 0;
printf( "Among the first %u items of Fibonacci series there are ", n );
for (unsigned int i = 0; i < n; i++ )
{
if ( is_prime( fibonacci1 ) )
{
if (present == 0) printf( "also prime " );
present = 1;
printf( "%u ", fibonacci1 );
}
fibonacci2 = fibonacci1 + fibonacci2;
fibonacci1 = fibonacci2 - fibonacci1;
}
if (present == 0) printf( "no prime numbers." );
puts( "\n" );
}
}
程序输出可能看起来像
Please enter the number of Fibonacci items (0 - exit): 10
Among the first 10 items of Fibonacci series there are also prime 2 3 5 13
Please enter the number of Fibonacci items (0 - exit): 6
Among the first 6 items of Fibonacci series there are also prime 2 3 5
Please enter the number of Fibonacci items (0 - exit): 3
Among the first 3 items of Fibonacci series there are no prime numbers.
Please enter the number of Fibonacci items (0 - exit): 0