📜  O(log n)中用于复数幂的程序

📅  最后修改于: 2021-05-08 16:57:32             🧑  作者: Mango

给定x + yi形式的复数和整数n ,任务是计算此复数的值并n

例子:

Input: num = 17 - 12i, n = 3
Output: -2431 + i ( -8676 )

Input: num = 18 - 13i, n = 8
Output: 16976403601 + i ( 56580909840 )

方法:该算法以O(log n)时间复杂度工作。令c = a + bi并且n是指数,

power(x, n) {
    if(n == 1)
        return x
    sq = power(x, n/2);
    if(n % 2 == 0)
        return cmul(sq, sq);
    if(n % 2 != 0)
        return cmul(x, cmul(sq, sq));
}

由于复数有2个字段,一个是实数,另一个是复数,因此我们将其存储在数组中。我们使用cmul()函数将两个数组相乘,其中cmul()实现以下乘法。

If x1 = a + bi and x2 = c + di
then x1 * x2 = a * c - b * d + (b * c + d * a )i 

正如我们在power()函数看到的那样,对于输入减少1/2倍的输入,调用了同一函数。
T(n)= T(n / 2)+ c,因此T(n)= log n

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the product
// of two complex numbers
long long* cmul(long long* sq1, long long* sq2)
{
    long long* ans = new long long[2];
  
    // For real part
    ans[0] = (sq1[0] * sq2[0]) - (sq1[1] * sq2[1]);
  
    // For imaginary part
    ans[1] = (sq1[1] * sq2[0]) + sq1[0] * sq2[1];
  
    return ans;
}
  
// Function to return the complex number
// raised to the power n
long long* power(long long* x, long long n)
{
    long long* ans = new long long[2];
    if (n == 0) {
        ans[0] = 0;
        ans[1] = 0;
        return ans;
    }
    if (n == 1)
        return x;
  
    // Recursive call for n/2
    long long* sq = power(x, n / 2);
    if (n % 2 == 0)
        return cmul(sq, sq);
    return cmul(x, cmul(sq, sq));
}
  
// Driver code
int main()
{
    int n;
    long long* x = new long long[2];
  
    // Real part of the complex number
    x[0] = 18;
  
    // Imaginary part of the complex number
    x[1] = -13;
    n = 8;
  
    // Calculate and print the result
    long long* a = power(x, n);
    cout << a[0] << " + i ( " << a[1] << " )" << endl;
  
    return 0;
}


Python 3
# Python3 implementation of the approach
  
# Function to return the product
# of two complex numbers
def cmul(sq1, sq2):
  
    ans = [0] * 2
  
    # For real part
    ans[0] = ((sq1[0] * sq2[0]) - 
              (sq1[1] * sq2[1]))
  
    # For imaginary part
    ans[1] = ((sq1[1] * sq2[0]) + 
               sq1[0] * sq2[1])
  
    return ans
  
# Function to return the complex 
# number raised to the power n
def power(x, n):
  
    ans = [0] * 2
    if (n == 0):
        ans[0] = 0
        ans[1] = 0
        return ans
      
    if (n == 1):
        return x
  
    # Recursive call for n/2
    sq = power(x, n // 2)
    if (n % 2 == 0):
        return cmul(sq, sq)
    return cmul(x, cmul(sq, sq))
  
# Driver code
if __name__ == "__main__":
  
    x = [0] * 2
  
    # Real part of the complex number
    x[0] = 18
  
    # Imaginary part of the
    # complex number
    x[1] = -13
    n = 8
  
    # Calculate and print the result
    a = power(x, n)
    print(a[0], " + i ( ", a[1], " )")
  
# This code is contributed by ita_c


PHP


输出:
16976403601 + i ( 56580909840 )