Skip to content

Instantly share code, notes, and snippets.

@krypt-lynx
Created April 14, 2015 21:56
Show Gist options
  • Save krypt-lynx/4326359b748c5f4b9cc8 to your computer and use it in GitHub Desktop.
Save krypt-lynx/4326359b748c5f4b9cc8 to your computer and use it in GitHub Desktop.
static BigInteger ProdTree(int l, int r)
{
if (l > r)
return 1;
if (l == r)
return l;
if (r - l == 1)
return (BigInteger)l * r;
int m = (l + r) / 2;
return ProdTree(l, m) * ProdTree(m + 1, r);
}
const int threadCount = 2;
static Task<BigInteger> AsyncProdTree(int l, int r)
{
return Task<BigInteger>.Run(() => ProdTree(l, r));
}
static BigInteger FactThreadingTree(int n)
{
if (n < 0)
return 0;
if (n == 0)
return 1;
if (n == 1 || n == 2)
return n;
if (n < threadCount+1)
return ProdTree(2, n);
Task<BigInteger>[] tasks = new Task<BigInteger>[threadCount];
tasks[0] = AsyncProdTree(2, n / threadCount);
for (int i = 1; i < threadCount; i++)
{
tasks[i] = AsyncProdTree(((n / threadCount) * i) + 1, (n / threadCount) * (i + 1));
}
Task<BigInteger>.WaitAll(tasks);
BigInteger result = 1;
for (int i = 0; i < threadCount; i++)
{
result *= tasks[i].Result;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment