如何编写一个程序,由用户F0,F1和fmax输入3个输入,并输出所有的素数Fibonnaci数?

yftpprvb  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(134)

这段代码总是跳过前两个斐波那契数,它们是质数(F0和F1),我需要写一个广义斐波那契序列,它们也是质数。其中Fn =Fn−1 +Fn−2,我知道我的问题在循环中,但我没有弄清楚。

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #define false 0
  4. #define true 1
  5. int main(int argc, char **argv)

{

  1. int NN, PN, i, terms;
  2. int F0;
  3. int F1;
  4. int Fmax;
  5. char *p;
  6. terms = Fmax = strtol(argv[3], &p, 10);
  7. F0 = strtol(argv[1], &p, 10);;
  8. F1 = strtol(argv[2], &p, 10);
  9. F0 = strtol(argv[1], &p, 10);
  10. if (*p != '\0')
  11. {
  12. return 1;
  13. }
  14. F1 = strtol(argv[2], &p, 10);
  15. if (*p != '\0')
  16. {
  17. return 1;
  18. }
  19. Fmax = strtol(argv[3], &p, 10);
  20. if (*p != '\0')
  21. {
  22. return 1;
  23. }
  24. if (argc != 4)
  25. {
  26. printf("Error: Please enter only 3 values, for F0, F1 and Fmax\n");
  27. return 1;
  28. }
  29. if (F0 < 1 || F1 < 1 || Fmax < 1)
  30. {
  31. printf("Error: Please put only positive values\n");
  32. }
  33. if (F0 > F1)
  34. {
  35. printf("Error: F0 can not be bigger than F1\n");
  36. }
  37. if (Fmax < F1)
  38. {
  39. printf("Error: Fmax can`t be less than F1\n");
  40. }
  41. if (F0 < 1 || Fmax > 1000000)
  42. {
  43. printf("Error: Please enter a value between 1 and 1000000\n");
  44. return 1;
  45. }

我相信问题就在这里,但我试着把术语设置为Fmax,实际上我在网上看到了一些代码,它们应该有同样的目的。

  1. else
  2. {
  3. if (F1 == 2)
  4. {
  5. printf("2\n");
  6. }
  7. for(i = 0; i < terms; i++)
  8. {
  9. NN = F0 + F1;
  10. F0 = F1;
  11. F1 = NN;
  12. for(PN = 3; PN <= NN; PN++)
  13. {
  14. if(PN == NN)
  15. printf("%d\n", NN);
  16. if (NN > Fmax)
  17. break;
  18. if (NN % PN == 0)
  19. break;
  20. }
  21. }
  22. }
  23. return 0;

}

ctrmrzij

ctrmrzij1#

这应该足够了:

  1. #include <iostream>
  2. using namespace std;
  3. int main(){
  4. int f0, f1, fn;
  5. cin >> f0 >> f1 >> fn;
  6. while(f0 <= fn){
  7. if(isPrime(f0)) cout << f0 << '\n';
  8. f1 = f0+f1;
  9. f0 = f1-f0;
  10. }
  11. return 0;
  12. }

现在,关于这个问题的一个重要的评论:
如果你想知道f(n)是否是素数,你可以使用线性递归来找到一个封闭的公式来知道这个值。f(n) = Fib(n-1)*(f(0)+f(1)) + Fib(n-2)*f(1)
从这个封闭的公式中,你可以分辨出一些重要的事实:
1.如果gcd(f(0), f(1)) != 1 .然后,在你的序列中没有素数(当然忽略f(0)f(1))。
1.如果f(1)%Fib(n-1) == 0 .因此,f(n)不是质数。
1.如果Fib(n-2)%(f0+f1) == 0 .因此,f(n)不是质数。
函数isPrime(n)是一个高效函数,如果n是素数,则返回true,否则返回false
有关该函数的更多信息,您可以搜索primality testing作为Miller-Rabin算法。

展开查看全部

相关问题