📜  查找前N个Fermat编号的程序

📅  最后修改于: 2021-05-04 07:50:16             🧑  作者: Mango

费马数是非负奇数,对k> = 0的所有值均有效。到目前为止,只有序列的前七个术语是已知的。首先,该系列的五个术语是主要的,而其余的则不是。费马数的第k个项表示为


序列:

对于给定的N ,任务是找到前N个Fermat数。

例子:

方法 :
使用上述公式,我们将找到级数的N个项。

下面是上述方法的实现:

C++
// CPP program to print fermat numbers
#include 
#include 
using namespace boost::multiprecision;
#define llu int128_t
using namespace std;
  
/* Iterative Function to calculate (x^y) in O(log y) */
llu power(llu x, llu y)
{
    llu res = 1; // Initialize result
  
    while (y > 0) {
        // If y is odd, multiply x with the result
        if (y & 1)
            res = res * x;
  
        // n must be even now
        y = y >> 1; // y = y/2
        x = x * x; // Change x to x^2
    }
    return res;
}
  
// Function to find nth fermat number 
llu Fermat(llu i)
{
    // 2 to the power i
    llu power2_i = power(2, i);
  
    // 2 to the power 2^i
    llu power2_2_i = power(2, power2_i);
  
    return power2_2_i + 1;
}
  
// Function to find first n Fermat numbers
void Fermat_Number(llu n)
{
      
    for (llu i = 0; i < n; i++) {
          
        // Calculate 2^2^i
        cout << Fermat(i);
          
        if(i!=n-1)
            cout << ", ";
    }
}
  
// Driver code
int main()
{
    llu n = 7;
      
    // Function call
    Fermat_Number(n);
  
    return 0;
}


Python3
# Python3 program to print fermat numbers
  
# Iterative Function to calculate (x^y) in O(log y) 
def power(x, y):
  
    res = 1 # Initialize result
  
    while (y > 0):
          
        # If y is odd, 
        # multiply x with the result
        if (y & 1):
            res = res * x
  
        # n must be even now
        y = y >> 1 # y = y/2
        x = x * x # Change x to x^2
    return res
  
# Function to find nth fermat number
def Fermat(i):
      
    # 2 to the power i
    power2_i = power(2, i)
  
    # 2 to the power 2^i
    power2_2_i = power(2, power2_i)
  
    return power2_2_i + 1
  
# Function to find first n Fermat numbers
def Fermat_Number(n):
  
    for i in range(n):
  
        # Calculate 2^2^i
        print(Fermat(i), end = "")
  
        if(i != n - 1):
            print(end = ", ")
  
# Driver code
n = 7
  
# Function call
Fermat_Number(n)
  
# This code is contributed by Mohit Kumar


输出:

3, 5, 17, 257, 65537, 4294967297, 18446744073709551617


参考:
https://en.wikipedia.org/wiki/Fermat_number