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:



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

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

   return sum; 



float CalcGeoSum(float a1, float a2, int n){
   float k, sum = 0.0;
   k = a2/a1; 
   if(k <= 1)
       sum = 0.0; 
       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");

Invoke in C++:

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

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,