[英](C++) Program to print all prime numbers in the a Fibonacci sequence
有人可以幫我嗎? 我一直在嘗試讓這個程序打印並添加斐波那契數列中 1000 以下的所有素數。只需輸入常規斐波那契代碼就可以正常工作,並將列出數字 1 - 987。
然而,當我輸入質數檢查器時,它突然停在 5(打印“1 1 2 3 5”,這在技術上是正確的,因為它們都屬於質數(盡管 1 不算) 。但是,我希望看到序列中從 1 到 987 的所有素數,無論我做什么,我似乎都無法讓它工作。
我的代碼在下面,不要介意缺少主要功能,我正在將此功能作為更大程序的一部分,但它可以獨立存在。 目前通過在主函數中調用它來測試它。
#include <iostream>
using namespace std;
void primethousand() {
int fibo = 1;
int nacci = 1;
int fibonacci = 0;
int fibosum = 0; //used to get the sum of all printed numbers later, once this issue is fixed.
int pchk = 0; /*primecheck, used to check if a number is a prime or not. 1 means not prime, 0 means prime*/
cout << "\nPrime Fibonacci #s under 1000: \n\n";
for (int ctr = 1; fibonacci < 987; ctr++) {
if (ctr == 1) {
cout << fibo << " ";
continue;
} else if (ctr == 2) {
cout << nacci << " ";
continue;
}
fibonacci = fibo + nacci;
fibo = nacci;
nacci = fibonacci;
//cout << fibonacci << " ";
for (int chr = 2; chr < fibonacci; chr++) {
if (fibonacci % chr == 0) {
pchk = 1;
}
}
if (pchk == 0) {
cout << fibonacci << " ";
}
}
}
看起來一旦 pchk 設置為 1,您就永遠不會將其設置回零,因此永遠不會注意到更多的素數。
您應該使用函數將大任務分解為更小的任務。
此外,斐波那契數列呈指數級增長。 所以,在C++標准數據類型中可以計算的數字並不多。 例如,即使是最大的 8 字節unsigned long long
或uint64_t
也只能容納斐波那契數列的第 94 個元素。
對於低於 1000 的斐波納契,它將只有 16 個元素。
因此,我們可以在編譯時輕松地預先計算所有值(因此,而不是在運行時)。 這將是最快的解決方案。 編譯時間也會很短。 而且內存消耗會很低。
請參見:
#include <iostream>
#include <array>
#include <cstdint>
// For fibonacci number < 1000, 16 of the series elements will be sufficient
constexpr std::size_t ArraySize{ 16 };
// Calculate all 16 needed fibonacci number during compile time
consteval auto CreateFibonacciNumberArray() {
std::array<std::uint64_t, ArraySize> fs{ 1, 1 };
for (std::size_t i{ 2 }; i < ArraySize; ++i)
fs[i] = fs[i - 1] + fs[i - 2];
return fs;
}
// This is an array with the 16 fibonacci numbers. It is an compile time array
constexpr auto FIB = CreateFibonacciNumberArray();
// Compiletime function to calculate, if fibonacci numbers are prime
constexpr bool isPrime(const std::uint64_t number) {
if (number % 2 == 0 or number <= 2) return false;
for (std::uint64_t i = 3; (i * i) <= number; i += 2)
if (number % i == 0) return false;
return true;
}
// Create a compile time array, to indicate, if a fibnacci number is prinme
consteval auto IsPrime(const std::array<std::uint64_t, ArraySize>& FIB) {
std::array<bool, ArraySize> primeFibonacci{};
for (std::size_t i{}; i < ArraySize; ++i)
primeFibonacci[i] = isPrime(FIB[i]);
return primeFibonacci;
}
// Boolean compile time array that shows, if a fibonacci number is prime
constexpr auto FibIsPrime = IsPrime(FIB);
int main()
{
for (std::size_t i{}; i < ArraySize; ++i) {
std::cout << FIB[i];
if (FibIsPrime[i]) std::cout << "\tis prime";
std::cout << '\n';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.