I'm trying to develop a simple program to evaluate integral powers of a complex number \$z\$ , that is, \$z^n\$, where \$z\$ is in the algebrical form \$a+i b\$ and \$n \in \mathbb{Z} ^{*} _{+}\$.

How I was trying to proceed:

First, I defined a product function, and next I intended to define a exponentiation function inside of which I iterated the product function (the code can bee seen below). Is it correct? Is there a more efficient alternative for doing that?

    include <stdio.h>
    include <math.h>

    struct complex {
        float real,imag;

    struct complex product (struct complex x, struct complex y){
    /* using the distributive property, (a+ib)(c+id) = (ac-bd)+i(ad+bc)*/
        struct complex z;
        z.real = (x.real * y.real)- (x.imag * y.imag);
        z.imag = (x.real * y.imag) + (x.imag * y.real);
    return z;

    struct complex exponentiation (struct complex z, int n){
        int i;
        struct complex w;
        w = z;
        for (i=1, i<n, i++)
            w = product (w,z);
    return w;

C has a built-in complex type and a cpow() function since C99. You seem to be .

Only in rare circumstances should you use float. In most cases, you should use double instead.

Exponentiation of complex numbers is better done using the polar representation:

$$z = r e^{i\theta}$$


$$\begin{align} z &= a + i b \\ r &= \sqrt{a^2 + b^2} \\ \theta &= \arctan{\frac{b}{a}} \end{align}$$


$$z^n = (r e^{i\theta})^n = r\,^n e^{i\ n \theta}$$

For non-trivial values of \$n\$, you would be better off converting to a polar representation, performing the exponentiation, and converting back to the Cartesian representation.

  • Your algorithm is linear with respect to the exponent. It could (and should) be done in a logarithmic time.

  • complex exponentiation (struct complex z, int n) as coded returns wrong answer for non-positive n.

  • \$\begingroup\$ To be fair, it is declared in the question that n ∈ ℤ∗+. Perhaps the problem is that it doesn't validate that n > 0. \$\endgroup\$ Mar 3 '15 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.