tags:

views:

207

answers:

1

Someone can explain that code please ?

using System;

class Program {

static int[] p = new int[4] { 2, 3, 5, 7 };

static double sum = 0, max = Math.Pow(10, 100);

static void Main(string[] args)
{
    for (int i = 0; i < p.Length; i++)
        f(1, p[i], i);
    Console.WriteLine(sum);
}

static void f(double produit, int val, int pos)
{
    produit *= val;
    if (produit < max)
    {
        sum += produit;
        for (int i = pos; i < p.Length; i++)
            f(produit, p[i], i);
    }
}

}

+7  A: 

Basically you can reduce the code to:

f(produit, 2, 1);

static void f(double produit, int val, int pos)
{
    produit *= val;
    if (produit < max)
    {
        sum += produit;
        f(produit, 2, 1);
    }
}

Since the code is recursive and doesn't change any input parameters it will just calculate
f(product, 2, 1) ... that means it will calculate 2^n until this value exceeds 10^100 ... and during this time sum the poducts (2^333 will be greater than 10^100 ... so the code will execute 332 times).

EDIT:
And what's sum in the end? As far as I can tell the code sums 2+4+8+16+ ... +2^332. As Yury pointed out, thats simply 2^333-2 :)

tanascius
By the way 2+4+8+16+...+2^332 = 2^333-2 :)
Yury Tarabanko
@Yury ... you are right, of course, thx
tanascius