Created
July 25, 2017 06:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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