lucas_sequences_U_V_mpz.pl 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/perl
  2. # Algorithm due to Aleksey Koval for computing the Lucas U and V sequences.
  3. # See also:
  4. # https://en.wikipedia.org/wiki/Lucas_sequence
  5. use 5.020;
  6. use warnings;
  7. use experimental qw(signatures);
  8. use Math::GMPz;
  9. sub lucasUV ($n, $P, $Q) {
  10. $n = Math::GMPz->new("$n");
  11. $P = Math::GMPz->new("$P");
  12. $Q = Math::GMPz->new("$Q");
  13. my ($V1, $V2) = (Math::GMPz::Rmpz_init_set_ui(2), Math::GMPz::Rmpz_init_set($P));
  14. my ($Q1, $Q2) = (Math::GMPz::Rmpz_init_set_ui(1), Math::GMPz::Rmpz_init_set_ui(1));
  15. my $t = Math::GMPz::Rmpz_init();
  16. my $v = Math::GMPz::Rmpz_init();
  17. foreach my $bit (split(//, Math::GMPz::Rmpz_get_str($n, 2))) {
  18. Math::GMPz::Rmpz_mul($Q1, $Q1, $Q2);
  19. if ($bit) {
  20. Math::GMPz::Rmpz_mul($Q2, $Q1, $Q);
  21. Math::GMPz::Rmpz_mul($V1, $V1, $V2);
  22. Math::GMPz::Rmpz_mul($t, $P, $Q1);
  23. Math::GMPz::Rmpz_mul($V2, $V2, $V2);
  24. Math::GMPz::Rmpz_sub($V1, $V1, $t);
  25. Math::GMPz::Rmpz_submul_ui($V2, $Q2, 2);
  26. }
  27. else {
  28. Math::GMPz::Rmpz_set($Q2, $Q1);
  29. Math::GMPz::Rmpz_mul($V2, $V2, $V1);
  30. Math::GMPz::Rmpz_mul($t, $P, $Q1);
  31. Math::GMPz::Rmpz_mul($V1, $V1, $V1);
  32. Math::GMPz::Rmpz_sub($V2, $V2, $t);
  33. Math::GMPz::Rmpz_submul_ui($V1, $Q2, 2);
  34. }
  35. }
  36. Math::GMPz::Rmpz_mul_2exp($t, $V2, 1);
  37. Math::GMPz::Rmpz_submul($t, $P, $V1);
  38. Math::GMPz::Rmpz_mul($v, $P, $P);
  39. Math::GMPz::Rmpz_submul_ui($v, $Q, 4);
  40. Math::GMPz::Rmpz_divexact($t, $t, $v);
  41. return ($t, $V1);
  42. }
  43. foreach my $n (1 .. 20) {
  44. say "[", join(', ', lucasUV($n, 1, -1)), "]";
  45. }
  46. __END__
  47. [1, 1]
  48. [1, 3]
  49. [2, 4]
  50. [3, 7]
  51. [5, 11]
  52. [8, 18]
  53. [13, 29]
  54. [21, 47]
  55. [34, 76]
  56. [55, 123]
  57. [89, 199]
  58. [144, 322]
  59. [233, 521]
  60. [377, 843]
  61. [610, 1364]
  62. [987, 2207]
  63. [1597, 3571]
  64. [2584, 5778]
  65. [4181, 9349]
  66. [6765, 15127]