Skip to content

Instantly share code, notes, and snippets.

@sikinmettugi
Created July 25, 2017 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sikinmettugi/1e2bb3764936ae424a2018a4bb9acf1e to your computer and use it in GitHub Desktop.
Save sikinmettugi/1e2bb3764936ae424a2018a4bb9acf1e to your computer and use it in GitHub Desktop.
Generate Product Except Self % m(== f), add all of them, then % m(== g), return g
int productExceptSelf(int[] nums, int m) {
var query = from i in Enumerable.Repeat(1, nums.Length)
select (Int64)i;
Int64[] prefixProducts = query.ToArray();
Int64[] postfixProducts = query.ToArray();
// Generate f
for (int i = 1; i < nums.Length; i++)
{
prefixProducts[i] = nums[i - 1] * prefixProducts[i - 1];
}
for (int i = nums.Length - 2; i >= 0; i--)
{
postfixProducts[i] = nums[i + 1] * postfixProducts[i + 1];
}
var FValues = prefixProducts.Zip(postfixProducts, (i, j) => i*j % m);
// Debug print
foreach (var i in FValues)
{
Console.Write($"{i}, ");
}
Console.WriteLine();
var GValue = (int)FValues.Aggregate((sum, x) => sum + x);
return GValue % m;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment