Skip to content

Instantly share code, notes, and snippets.

@MeinLiX
Last active June 7, 2021 09:14
Show Gist options
  • Save MeinLiX/c53cb2bfb76ef9b6c0747f0510ae17e9 to your computer and use it in GitHub Desktop.
Save MeinLiX/c53cb2bfb76ef9b6c0747f0510ae17e9 to your computer and use it in GitHub Desktop.
.net 5, MPI factorial
using System;
using System.Diagnostics;
using System.Numerics;
MPI.Environment.Run(ref args, comm =>
{
if (comm.Rank == 0)
{
BigInteger x = BigInteger.Parse(args[0]);
BigInteger res = 1;
Stopwatch watch = new();
watch.Start();
for (int i = 1; i < comm.Size; i++)
comm.Send(new Pair(((i - 1) * x / (comm.Size - 1)) + 1, i * x / (comm.Size - 1)), i, 0);
for (int i = 1; i < comm.Size; i++)
res *= comm.Receive<BigInteger>(i, 0);
watch.Stop();
Console.WriteLine($"{x}! = {res} | {watch.Elapsed.TotalMilliseconds}(ms)");
}
else
{
Pair res = comm.Receive<Pair>(0, 0);
comm.Send(factorial(res.A, res.B), 0, 0);
}
});
static BigInteger factorial(BigInteger a, BigInteger b)
{
BigInteger res = a;
while (a < b) res *= ++a;
return res * b;
}
[Serializable]
class Pair
{
public BigInteger A { get; set; }
public BigInteger B { get; set; }
public Pair(BigInteger a, BigInteger b)
{
A = a;
B = b;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment