Uczę się rekurencji, mam problem

0

Cześć wszystkim, próbuję zrozumieć rekurencję poprzez rozwiązanie tego przykładu:

namespace ConsoleApp25
{
    class Program
    {
        //W = (x+1) + (x+2) + (x+3) +.......+ (x+n).
        static int Rekurencja(int x, int n)
        {
            if (x == 0)
                return 1;
            return x + Rekurencja(x - 1, n);
        }

        static void Main(string[] args)
        {
            Console.Write("Podaj x: ");
            int x = int.Parse(Console.ReadLine());
            Console.Write("Podaj n: ");
            int n = int.Parse(Console.ReadLine());

            Console.WriteLine(Rekurencja(x, n));

        }
    }
}

Niestety robię to źle i nie wiem jak poprawić ten kod, aby rekurencja była użyta poprawnie.

2
static int Rekurencja(int x, int n)
{
    if (n == 0)
    {
        return 0;
    }

    return x + n + Rekurencja(x, n - 1);
}

A jak to zrozumieć? Twój wzór

W(x, n) = (x + 1) + (x + 2) + ... + (x + n) 

zapisujesz jako

(x + 1) + (x + 2) + ... + (x + n - 1) + (x + n) = W(x, n - 1) + (x + n)
0

Co to znaczy "robię to źle"? Masz jakiś błąd? Źle liczy?

0
AdamWox napisał(a):

Co to znaczy "robię to źle"? Masz jakiś błąd? Źle liczy?

źle liczy

0

a gdzie w funkcji Rekurencje( int x, int n) używasz "n"?

1 użytkowników online, w tym zalogowanych: 0, gości: 1