在斐波那契数列中查找素数的c++程序

  • 本文关键字:c++ 程序 查找 数列 c++
  • 更新时间 :
  • 英文 :


有人能帮我一下吗?这是一个c++程序,我需要找到斐波那契数列的素数。问题是,在你输入n(斐波那契数列的个数)之后,程序必须从中提取质数,然后,如果这些质数的和是奇数,它必须显示A,如果是偶数,它应该显示D。问题是我知道如何找到斐波那契数列和质数,但我不会合并它们。我需要让代码尽可能的简单有人能帮我一下吗?

这个是fibonacci级数:

#include <iostream>
#include <conio.h>
using namespace std;
int main(){
int n, a = 1, b = 1, c;
cin >> n;
cout << a << endl;
cout << b << endl;
int i = 2;
while (i < n)
{
c = a + b;
cout << c << endl; 
a = b; 
b = c;   
i++;
}
getch();
}

这个是针对质数的

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int a, b = 1, r = 1, c = 0, x, m;
cout << "please enter number :";
cin >> a;
while (b <= a) {
m = a;
x = b;
while (x != 0) {
r = m % x;
m = x;
x = r;
}
if (m == 1){
c++;
b++;
}
cout << c;
getch();
}

我必须把它们放在一起,这样我就可以提取斐波那契中的质数,但我不知道怎么做。我需要它来显示质数但我的代码显示了有多少个数是质数

一个解决方案可以是编写一个函数来查找n'斐波那契数,另一个函数来测试一个数字是否为素数,然后循环遍历斐波那契数以查找素数

#include <iostream>
int fib(int n) { /* code */ }
bool is_prime(int n) { /* code */ }
int sum_of_prime_in_fib(int lim)
{
int sum = 0;
// loop over the fibonacci number to sum the primes
for (int i = 1; i <= lim; ++i) {
int f = fib(i);
if (is_prime(f))
sum += f;
}
return sum;
}
int main()
{
int n;
std::cout << "please enter number :";
std::cin >> n; //remember to check for errors, which I wont do
std::cout << "the sum of primes is: " << sum_of_prime_in_fib(n) << "n";
} 

我把这两个函数的实现留作练习

由于您没有包含conio.h内容,所以我将从根本上提出一个解决方案。

这个问题涉及到几个阶段。

  1. 获取所有fibonacci序列
  2. 使用斐波那契数列查找是否存在素数(将它们放在列表中)
  3. 计算该列表中质数的和
  4. 如果总和是偶数,打印"A"否则打印"D"

代码可以分解为几个函数,使其更容易和更直观。

#include <iostream>
#include <conio.h>
#include <vector>
using namespace std;

vector<int> generate_fibonacci(int n){
int a = 1, b = 1, c;
//cout << a << endl;
//cout << b << endl;
int i = 2; 
vector<int> f;
f.push_back(a);
f.push_back(b);//assuming that the a,b are part of the fibonacci

while (i < n)
{
c = a + b;
f.push_back(c);
a = b; 
b = c;   
i++;
}
return f;
}
bool is_prime(int n)
{
// Corner case
if (n <= 1)
return false;

// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;

return true;
}
vector<int> find_prime_from_f(vector<int> v){
vector<int> fp;
for(int i: v){
if(is_prime(i))
{
fp.push_back(i);
}
}
return fp;
}
int main(){
cout << "please enter the number of fibonacci" << endl;
int n;
cin >> n;
vector<int> fibonacciNumber = generate_fibonacci(n);
vector<int> fibonacciPrime = find_prime_from_f(fibonacciNumber);
int sum;
for(int i: fibonacciPrime)
{
sum += i;
}
if(sum %2 != 0) cout << "A" <<endl; //if it is odd
else cout << "D" <<endl; //if it is even

}

当然,您可以定制这些函数的一些细节,包括添加一些负数的边界检查,并通过使用数组优化算法,动态地进行计算和检查,或者稍微简化代码。但是,这应该作为您进一步实现的起点。

最新更新