有人能在这方面帮我吗?这是一个c++程序,我需要找出斐波那契级数的素数。问题是,在你输入n(斐波那契数列的个数)之后,程序必须从中提取质数,然后,如果这些质数的和是奇数,它必须显示'A‘,如果它是偶数,它应该显示'D’。问题是我知道如何找到斐波那契级数和质数,但我不能合并它们。我需要保持代码尽可能简单,有人能在这方面帮我吗?
这个是斐波那契级数:
#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();
}
我必须把它们放在一起,这样我才能提取斐波那契公式中的质数,但我不知道怎么做。而且,我需要它来显示质数,但是我的代码显示有多少数字是质数
发布于 2021-01-23 04:01:13
一种解决方案是创建一个函数来查找第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";
}
我把这两个函数的实现留作练习
发布于 2021-01-23 04:18:23
由于您没有包含conio.h内容,因此我将提出一个简单的解决方案。
这个问题围绕着几个阶段。
获取列表中的所有斐波那契数列使用斐波那契数列查找是否存在任何质数(将它们放在一个list)
代码可以分解为几个函数,以使其更容易和更直观。
#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
}
当然,您可以定制这些函数的一些细节,包括为负数添加一些边界检查,并通过使用数组来优化算法,即时进行计算和检查,或者稍微简化代码。但是,这应该作为您进一步实现的起点。
https://stackoverflow.com/questions/65851772
复制相似问题