Search code examples
c#algebra

Calculate the algebraic expressions in C#


Calculate the algebraic expression Z, for which n is inputted by user. Use 2 for loops to solve the problem.

enter image description here

My code so far:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            float sum = 0;

            int n = int.Parse(Console.ReadLine());

            for (int i = 1; i <= n; i++)
            {
                float p = 1;
                for (int k = 1; k <= i + 2; k++)
                {
                    p *= (3 * k + 2);
                }

                sum += p;
            }

            Console.WriteLine(sum);
            Console.ReadLine();
        }
    }
}

I am getting the wrong results, and sometimes the same, in case 3 and 4 return 6200 (which is wrong + the same).


Solution

  • Use <= instead of < in the first for loop, and write i++ instead of i+=2.

    Also, you don't need to use float, as the result will always be an integer. Use long instead.