-3

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).

user2925251
  • 117
  • 1
  • 1
  • 6

2 Answers2

4

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.

Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
  • I did that and I am no longer getting the same results, however, I think the results are wrong still? For input 2, I get answer: 6600. I think the answer is 30 (if I did the math correctly?). – user2925251 Oct 29 '13 at 17:15
  • No. It got the correct solution. You were wrong. :) http://www.wolframalpha.com/input/?i=sum%28product%283k%2B2%2C+1..i%2B2%29%2C+1..2%29 – Igor Ševo Oct 29 '13 at 17:19
1

I suppose this line is wrong:

for (int i = 0; i < n; i += 2)

It should be

for (int i = 1; i <= n; i++)
Torben Schramme
  • 2,104
  • 1
  • 16
  • 28