Math Is Fun: Geometric Sequences and Sums with C# and (Native) C++

Mathematics is really fun sometimes; however, what makes it difficult is that it is a fundamentally different way of thinking—for example, learning languages can be much easier than learning math.

Since I’ve been playing with geometrical sums and sequences I decided to try this out with some computer programming, so I wrote two methods in two different languages, one in C++ and the other one in C#.

I’ll be using the following geometric sum formula:

C#:

static double CalcGeoSum(double a1, double a2, int n)
{
   double k, sum = 0;
   k = a2 / a1;

   if (k <= 1)
       sum = 0; 
   else
       sum = (a1 * (Math.Pow(k, n) - 1)) / (k - 1);

   return sum; 
}

 

C++:

float CalcGeoSum(float a1, float a2, int n){
   float k, sum = 0.0;
   k = a2/a1; 
   
   if(k <= 1)
       sum = 0.0; 
   else 
       sum = (a1 * (pow(k, n)-1))/(k-1);
   
   return sum; 
}

It’s simple to invoke this function in any of the programming languages, just invoke it and pass it the required arguments. See the example below:

Invoke in C#:

static void Main(string[] args)
{
    Console.WriteLine(Convert.ToString(CalcGeoSum(3, 18, 6)) + "\n\n");
    Console.ReadKey(); 
}

Invoke in C++:

void main(){
    float result = CalcGeoSum(3, 18, 6); 
    cout << result << endl; 
	
    system("pause"); 
}

The output when you compile an run one of these code snippets in debug mode will be:

Output in C#: 27993
Output in C++: 27993

For further reading, I recommend MathWorld,
http://mathworld.wolfram.com/GeometricSeries.html

Leave a Reply