gpt4 book ai didi

c++ - 如何从 C++ 中的斐波那契数列中提取质数?

转载 作者:行者123 更新时间:2023-11-27 22:51:56 24 4
gpt4 key购买 nike

请帮助我的代码如下。我已经成功地找到了一个范围内的斐波那契数列,但我发现很难从斐波那契数列中提取素数。质数部分似乎有很多错误。请帮忙。谢谢

#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();
}
}

最佳答案

根据 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 要求更新:完整代码,无 vector
注意: 在提取素数时,为了将它们与斐波那契分开输出,您必须将它们存储在某个地方。由于您不使用 vector ,我将使用数组来实现它。
数组的问题是,你必须用一个大小来声明它们,但你不知道在你声明它的那一刻你会得到多少素数。所以你必须声明数组的大小足以包含斐波那契数列中的所有素数

#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] << " ";
}

关于c++ - 如何从 C++ 中的斐波那契数列中提取质数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36417069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com