How to efficiently find the sum of (1/a^2x) without using the power function?

Viewed 71

I need to calculate the sum of the number a (double) to the power of n (int) in C programming language. Without the pow function!

I have done it this way, but it is very complex, I want something simpler.

If you know how to make this via Java or C++ or Pascal please reply too)

1/a2 + 1/a4 + 1/a6 ... + 1/a2n.

program sum;
 
var i, n: integer;
    s, a, x: real;
    f: boolean;
 
begin
  repeat
    write('n = '); readln(n);
    if n < 1 then writeln('Error: n <= 0, reenter.')
  until n >= 1;
  repeat
    write('a = '); readln(a);
    if a = 0 then writeln('Error: a = 0, reenter.')
  until a <> 0;
  s := 0;
  x := 1;
  f := true;
  for i := 1 to n do
    begin
      x := x / a / a;
      if x = 0
        then begin
          writeln('Float rounding error.');
          f := false;
          break
        end;
      s := s + x
    end;
  if f then writeln('s = ', s);
  readln
end;
2 Answers

In C:

double bPow = 1;
double sum = 0
double b = a * a;

for (int i = 0; i < n; i++)
{
    bPow *= b;
    sum += 1 / bPow;
}

This gives you the sum of all 1/a^x for x = [2, 4, ..., 2n] .

The simpler way to do this is use a while loop. Here I used sum as s, base as b, and power as p.

Program in C language:

#include <stdio.h>

void main() {
    
    int s=1, b, p;
    
    printf("\nEnter the base value :");
    scanf("%i",&b);
    
    printf("\nEnter the power value :");
    scanf("%i",&p);
    
    while( p != 0)
    {
        s = s * b;
        
        p--;
    }
    
    printf("\nThe Sum  : %i", s);
    
    getch();
}
Related