请帮助我的代码如下。我已经成功地在一个范围内找到了斐波纳契数列,但我发现很难从斐波那契数列中提取素数。素数部分似乎有很多错误。请帮忙。感谢
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, c, first = 0, second = 1, next, flag;
cout << "Enter the number of terms of Fibonacci series you want" << endl;
cin >> n;
cout << "First " << n << " terms of Fibonacci series are :- " << endl;
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
cout << next << endl;
for (int j = 2; j<next; j++)
{
if (next%j == 0)
{
flag++;
}
if (flag == 0)
{
cout << "Prime numbers are" << next << "\t";
}
}
getch();
}
}
答案 0 :(得分:3)
更新为Rolland提及,我进行了编辑,以便sqrt只计算一次,哦1不是素数,傻我
检查素数
#include <math.h>
bool isPrime(int n)
{
if (n <= 1) return false;
if (n == 2 || n == 3) return true;
int checkRange = sqrt(n);
for (int i = 2; i <= checkRange; i++)
{
if (n % i == 0)
return false;
}
return true;
}
然后将它们存储在一个集合中并使用另一个循环将其打印出来
#include <vector> //Include this - vector is a standard c++ container
//Declare in your function
std::vector<int> primes;
//In your code where you get your next fibbonacci
if (isPrime(next))
primes.push_back(next);
//After you finished looping for fibbonacci
cout << endl << "Prime numbers are" << endl;
for (int i = 0; i < primes.size(); i++)
cout << primes[i] << " ";
以OP请求更新:Fullcode,无向量
注意: 在提取质数时,为了使用fibbonacci单独输出它们,您必须将它们存储在某处。由于你不使用矢量,我将用数组来实现它
数组的问题是,你必须用一个大小声明它们,但是你不知道在你声明它的那一刻你会得到多少素数。因此,您必须声明数组的大小足以包含fibbonacci中的所有素数
#include <iostream>
#include <math.h>
#define MAX 100
using namespace std;
bool isPrime(int n)
{
if (n <= 1) return false;
if (n == 2 || n == 3) return true;
int checkRange = sqrt(n);
for (int i = 2; i <= checkRange; i++)
{
if (n % i == 0)
return false;
}
return true;
}
void main()
{
int n, c, first = 0, second = 1, next, primeCount = 0;
int primes[MAX];
cout << "Enter the number of terms of Fibonacci series you want" << endl;
cin >> n;
cout << "First " << n << " terms of Fibonacci series are :- " << endl;
for (c = 0; c < n; c++)
{
if (c <= 1)
next = c;
else
{
next = first + second;
first = second;
second = next;
}
cout << next << endl;
if (isPrime(next)) //Reuse the above isPrime
{
primes[primeCount] = next;
primeCount++;
}
}
for (c = 0; c < primeCount; c++)
cout << primes[c] << " ";
}
答案 1 :(得分:1)
您可能希望先将flag
设置为0。