Skip to content

Instantly share code, notes, and snippets.

@tornikegomareli
Last active August 19, 2020 14:14
Show Gist options
  • Save tornikegomareli/066d95ec0d269de4b01f8825215d76b6 to your computer and use it in GitHub Desktop.
Save tornikegomareli/066d95ec0d269de4b01f8825215d76b6 to your computer and use it in GitHub Desktop.
Distributive factorial in C#
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace ParallelFactorial
{
class Program
{
static async Task Main(string[] args)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var result = await Factorial(1000);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine(elapsedMs);
Console.WriteLine("Result = " + result);
Console.ReadLine();
}
public async static Task<long> Factorial(int x)
{
int nr = x;
var tasks = new List<Task<long>>();
for (int i = 0; i < nr; i += (nr / 4))
{
int step = i;
tasks.Add(Task.Run(() =>
{
int right = (step + nr / 4) > nr ? nr : (step + nr / 4);
return ChunkFactorial(step + 1, right);
}));
}
await Task.WhenAll(tasks.ToArray());
return tasks.Select(t => t.Result).Aggregate(((i, next) => i * next));
}
public static long ChunkFactorial(int left, int right)
{
Console.WriteLine("ChunkFactorial Thread ID :" + Thread.CurrentThread.ManagedThreadId);
if (left == right)
return left == 0 ? 1 : left;
else return right * ChunkFactorial(left, right - 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment