Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Rewrite this program in VB while keeping its functionality equivalent to the Delphi version.
program ChineseRemainderTheorem; uses System.SysUtils, Velthuis.BigIntegers; function mulInv(a, b: BigInteger): BigInteger; var b0, x0, x1, q, amb, xqx: BigInteger; begin b0 := b; x0 := 0; x1 := 1; if (b = 1) then exit(1); while (a > 1) do begin q := a div b; amb := a mod b; a := b; b := amb; xqx := x1 - q * x0; x1 := x0; x0 := xqx; end; if (x1 < 0) then x1 := x1 + b0; Result := x1; end; function chineseRemainder(n: TArray<BigInteger>; a: TArray<BigInteger>) : BigInteger; var i: Integer; prod, p, sm: BigInteger; begin prod := 1; for i := 0 to High(n) do prod := prod * n[i]; p := 0; sm := 0; for i := 0 to High(n) do begin p := prod div n[i]; sm := sm + a[i] * mulInv(p, n[i]) * p; end; Result := sm mod prod; end; var n, a: TArray<BigInteger>; begin n := [3, 5, 7]; a := [2, 3, 2]; Writeln(chineseRemainder(n, a).ToString); end.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Convert this Delphi snippet to VB and keep its semantics consistent.
program ChineseRemainderTheorem; uses System.SysUtils, Velthuis.BigIntegers; function mulInv(a, b: BigInteger): BigInteger; var b0, x0, x1, q, amb, xqx: BigInteger; begin b0 := b; x0 := 0; x1 := 1; if (b = 1) then exit(1); while (a > 1) do begin q := a div b; amb := a mod b; a := b; b := amb; xqx := x1 - q * x0; x1 := x0; x0 := xqx; end; if (x1 < 0) then x1 := x1 + b0; Result := x1; end; function chineseRemainder(n: TArray<BigInteger>; a: TArray<BigInteger>) : BigInteger; var i: Integer; prod, p, sm: BigInteger; begin prod := 1; for i := 0 to High(n) do prod := prod * n[i]; p := 0; sm := 0; for i := 0 to High(n) do begin p := prod div n[i]; sm := sm + a[i] * mulInv(p, n[i]) * p; end; Result := sm mod prod; end; var n, a: TArray<BigInteger>; begin n := [3, 5, 7]; a := [2, 3, 2]; Writeln(chineseRemainder(n, a).ToString); end.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Write the same algorithm in Go as shown in this Delphi implementation.
program ChineseRemainderTheorem; uses System.SysUtils, Velthuis.BigIntegers; function mulInv(a, b: BigInteger): BigInteger; var b0, x0, x1, q, amb, xqx: BigInteger; begin b0 := b; x0 := 0; x1 := 1; if (b = 1) then exit(1); while (a > 1) do begin q := a div b; amb := a mod b; a := b; b := amb; xqx := x1 - q * x0; x1 := x0; x0 := xqx; end; if (x1 < 0) then x1 := x1 + b0; Result := x1; end; function chineseRemainder(n: TArray<BigInteger>; a: TArray<BigInteger>) : BigInteger; var i: Integer; prod, p, sm: BigInteger; begin prod := 1; for i := 0 to High(n) do prod := prod * n[i]; p := 0; sm := 0; for i := 0 to High(n) do begin p := prod div n[i]; sm := sm + a[i] * mulInv(p, n[i]) * p; end; Result := sm mod prod; end; var n, a: TArray<BigInteger>; begin n := [3, 5, 7]; a := [2, 3, 2]; Writeln(chineseRemainder(n, a).ToString); end.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Convert the following code from Delphi to Go, ensuring the logic remains intact.
program ChineseRemainderTheorem; uses System.SysUtils, Velthuis.BigIntegers; function mulInv(a, b: BigInteger): BigInteger; var b0, x0, x1, q, amb, xqx: BigInteger; begin b0 := b; x0 := 0; x1 := 1; if (b = 1) then exit(1); while (a > 1) do begin q := a div b; amb := a mod b; a := b; b := amb; xqx := x1 - q * x0; x1 := x0; x0 := xqx; end; if (x1 < 0) then x1 := x1 + b0; Result := x1; end; function chineseRemainder(n: TArray<BigInteger>; a: TArray<BigInteger>) : BigInteger; var i: Integer; prod, p, sm: BigInteger; begin prod := 1; for i := 0 to High(n) do prod := prod * n[i]; p := 0; sm := 0; for i := 0 to High(n) do begin p := prod div n[i]; sm := sm + a[i] * mulInv(p, n[i]) * p; end; Result := sm mod prod; end; var n, a: TArray<BigInteger>; begin n := [3, 5, 7]; a := [2, 3, 2]; Writeln(chineseRemainder(n, a).ToString); end.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Port the following code from Elixir to C with equivalent syntax and logic.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Generate an equivalent C version of this Elixir code.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Generate a C# translation of this Elixir snippet without changing its computational steps.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Preserve the algorithm and functionality while converting the code from Elixir to C#.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Port the following code from Elixir to C++ with equivalent syntax and logic.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Write a version of this Elixir function in C++ with identical behavior.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Change the following Elixir code into Java without altering its purpose.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Rewrite the snippet below in Java so it works the same as the original Elixir code.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Convert this Elixir snippet to Python and keep its semantics consistent.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Ensure the translated Python code behaves exactly like the original Elixir snippet.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Port the provided Elixir code into VB while preserving the original functionality.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Preserve the algorithm and functionality while converting the code from Elixir to VB.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Convert this Elixir block to Go, preserving its control flow and logic.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Generate a Go translation of this Elixir snippet without changing its computational steps.
defmodule Chinese do def remainder(mods, remainders) do max = Enum.reduce(mods, fn x,acc -> x*acc end) Enum.zip(mods, remainders) |> Enum.map(fn {m,r} -> Enum.take_every(r..max, m) |> MapSet.new end) |> Enum.reduce(fn set,acc -> MapSet.intersection(set, acc) end) |> MapSet.to_list end end IO.inspect Chinese.remainder([3,5,7], [2,3,2]) IO.inspect Chinese.remainder([10,4,9], [11,22,19]) IO.inspect Chinese.remainder([11,12,13], [10,4,12])
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Write a version of this Erlang function in C with identical behavior.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Can you help me rewrite this code in C instead of Erlang, keeping it the same logically?
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Produce a functionally identical C# code for the snippet given in Erlang.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Port the following code from Erlang to C# with equivalent syntax and logic.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Ensure the translated C++ code behaves exactly like the original Erlang snippet.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Generate an equivalent C++ version of this Erlang code.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Can you help me rewrite this code in Java instead of Erlang, keeping it the same logically?
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Change the following Erlang code into Java without altering its purpose.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Write a version of this Erlang function in Python with identical behavior.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Keep all operations the same but rewrite the snippet in Python.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Produce a functionally identical VB code for the snippet given in Erlang.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Change the following Erlang code into VB without altering its purpose.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Rewrite this program in Go while keeping its functionality equivalent to the Erlang version.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Transform the following Erlang implementation into Go, maintaining the same output and logic.
-module(crt). -import(lists, [zip/2, unzip/1, foldl/3, sum/1]). -export([egcd/2, mod/2, mod_inv/2, chinese_remainder/1]). egcd(_, 0) -> {1, 0}; egcd(A, B) -> {S, T} = egcd(B, A rem B), {T, S - (A div B)*T}. mod_inv(A, B) -> {X, Y} = egcd(A, B), if A*X + B*Y =:= 1 -> X; true -> undefined end. mod(A, M) -> X = A rem M, if X < 0 -> X + M; true -> X end. calc_inverses([], []) -> []; calc_inverses([N | Ns], [M | Ms]) -> case mod_inv(N, M) of undefined -> undefined; Inv -> [Inv | calc_inverses(Ns, Ms)] end. chinese_remainder(Congruences) -> {Residues, Modulii} = unzip(Congruences), ModPI = foldl(fun(A, B) -> A*B end, 1, Modulii), CRT_Modulii = [ModPI div M || M <- Modulii], case calc_inverses(CRT_Modulii, Modulii) of undefined -> undefined; Inverses -> Solution = sum([A*B || {A,B} <- zip(CRT_Modulii, [A*B || {A,B} <- zip(Residues, Inverses)])]), mod(Solution, ModPI) end.
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Maintain the same structure and functionality when rewriting this code in C.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Write the same algorithm in C as shown in this F# implementation.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Transform the following F# implementation into C#, maintaining the same output and logic.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Change the programming language of this snippet from F# to C# without modifying what it does.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Ensure the translated C++ code behaves exactly like the original F# snippet.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Convert the following code from F# to C++, ensuring the logic remains intact.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Preserve the algorithm and functionality while converting the code from F# to Java.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Produce a language-to-language conversion: from F# to Java, same semantics.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Convert this F# snippet to Python and keep its semantics consistent.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Generate a VB translation of this F# snippet without changing its computational steps.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Write the same algorithm in VB as shown in this F# implementation.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Maintain the same structure and functionality when rewriting this code in Go.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Change the following F# code into Go without altering its purpose.
let rec sieve cs x N = match cs with | [] -> Some(x) | (a,n)::rest -> let arrProgress = Seq.unfold (fun x -> Some(x, x+N)) x let firstXmodNequalA = Seq.tryFind (fun x -> a = x % n) match firstXmodNequalA (Seq.take n arrProgress) with | None -> None | Some(x) -> sieve rest x (N*n) [ [(2,3);(3,5);(2,7)]; [(10,11); (4,22); (9,19)]; [(10,11); (4,12); (12,13)] ] |> List.iter (fun congruences -> let cs = congruences |> List.map (fun (a,n) -> (a % n, n)) |> List.sortBy (snd>>(~-)) let an = List.head cs match sieve (List.tail cs) (fst an) (snd an) with | None -> printfn "no solution" | Some(x) -> printfn "result = %i" x )
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Convert this Factor snippet to C and keep its semantics consistent.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Port the provided Factor code into C while preserving the original functionality.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Translate the given Factor code snippet into C# without altering its behavior.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Port the following code from Factor to C# with equivalent syntax and logic.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Rewrite the snippet below in C++ so it works the same as the original Factor code.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Translate this program into C++ but keep the logic exactly as in Factor.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Rewrite the snippet below in Java so it works the same as the original Factor code.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Preserve the algorithm and functionality while converting the code from Factor to Java.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Keep all operations the same but rewrite the snippet in Python.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Change the following Factor code into Python without altering its purpose.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Rewrite this program in VB while keeping its functionality equivalent to the Factor version.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Ensure the translated VB code behaves exactly like the original Factor snippet.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Port the provided Factor code into Go while preserving the original functionality.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Ensure the translated Go code behaves exactly like the original Factor snippet.
USING: math.algebra prettyprint ; { 2 3 2 } { 3 5 7 } chinese-remainder .
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Keep all operations the same but rewrite the snippet in C.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Port the following code from Forth to C with equivalent syntax and logic.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Port the following code from Forth to C# with equivalent syntax and logic.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Ensure the translated C# code behaves exactly like the original Forth snippet.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Ensure the translated C++ code behaves exactly like the original Forth snippet.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Please provide an equivalent version of this Forth code in C++.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Translate this program into Java but keep the logic exactly as in Forth.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Generate a Java translation of this Forth snippet without changing its computational steps.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Generate an equivalent Python version of this Forth code.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Port the provided Forth code into Python while preserving the original functionality.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Produce a functionally identical VB code for the snippet given in Forth.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Convert the following code from Forth to VB, ensuring the logic remains intact.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Transform the following Forth implementation into Go, maintaining the same output and logic.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Produce a language-to-language conversion: from Forth to Go, same semantics.
: egcd dup 0= IF 2drop 1 0 ELSE dup -rot /mod -rot recurse >r swap r@ * - r> swap THEN ; : egcd>gcd rot * -rot * + ; : mod-inv 2dup egcd over >r egcd>gcd r> swap 1 <> -24 and throw ; : array-product 1 -rot cells bounds ?DO i @ * cell +LOOP ; : crt-from-array 2dup array-product locals| M count m[] a[] | 0 count 0 DO m[] i cells + @ dup M swap / dup rot mod-inv * a[] i cells + @ * + LOOP M mod ; create crt-residues[] 10 cells allot create crt-moduli[] 10 cells allot : crt 10 min locals| n | n 0 DO crt-moduli[] i cells + ! crt-residues[] i cells + ! LOOP crt-residues[] crt-moduli[] n crt-from-array ;
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Produce a functionally identical C code for the snippet given in Groovy.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Port the following code from Groovy to C with equivalent syntax and logic.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Ensure the translated C# code behaves exactly like the original Groovy snippet.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Keep all operations the same but rewrite the snippet in C#.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Convert this Groovy block to C++, preserving its control flow and logic.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Translate the given Groovy code snippet into C++ without altering its behavior.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Port the provided Groovy code into Java while preserving the original functionality.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Convert this Groovy snippet to Java and keep its semantics consistent.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Produce a language-to-language conversion: from Groovy to Python, same semantics.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Translate the given Groovy code snippet into Python without altering its behavior.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Write the same algorithm in VB as shown in this Groovy implementation.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Change the following Groovy code into VB without altering its purpose.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Maintain the same structure and functionality when rewriting this code in Go.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Preserve the algorithm and functionality while converting the code from Groovy to Go.
class ChineseRemainderTheorem { static int chineseRemainder(int[] n, int[] a) { int prod = 1 for (int i = 0; i < n.length; i++) { prod *= n[i] } int p, sm = 0 for (int i = 0; i < n.length; i++) { p = prod.intdiv(n[i]) sm += a[i] * mulInv(p, n[i]) * p } return sm % prod } private static int mulInv(int a, int b) { int b0 = b int x0 = 0 int x1 = 1 if (b == 1) { return 1 } while (a > 1) { int q = a.intdiv(b) int amb = a % b a = b b = amb int xqx = x1 - q * x0 x1 = x0 x0 = xqx } if (x1 < 0) { x1 += b0 } return x1 } static void main(String[] args) { int[] n = [3, 5, 7] int[] a = [2, 3, 2] println(chineseRemainder(n, a)) } }
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }
Transform the following Haskell implementation into C, maintaining the same output and logic.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Maintain the same structure and functionality when rewriting this code in C.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
#include <stdio.h> int mul_inv(int a, int b) { int b0 = b, t, q; int x0 = 0, x1 = 1; if (b == 1) return 1; while (a > 1) { q = a / b; t = b, b = a % b, a = t; t = x0, x0 = x1 - q * x0, x1 = t; } if (x1 < 0) x1 += b0; return x1; } int chinese_remainder(int *n, int *a, int len) { int p, i, prod = 1, sum = 0; for (i = 0; i < len; i++) prod *= n[i]; for (i = 0; i < len; i++) { p = prod / n[i]; sum += a[i] * mul_inv(p, n[i]) * p; } return sum % prod; } int main(void) { int n[] = { 3, 5, 7 }; int a[] = { 2, 3, 2 }; printf("%d\n", chinese_remainder(n, a, sizeof(n)/sizeof(n[0]))); return 0; }
Translate this program into C# but keep the logic exactly as in Haskell.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Write a version of this Haskell function in C# with identical behavior.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
using System; using System.Linq; namespace ChineseRemainderTheorem { class Program { static void Main(string[] args) { int[] n = { 3, 5, 7 }; int[] a = { 2, 3, 2 }; int result = ChineseRemainderTheorem.Solve(n, a); int counter = 0; int maxCount = n.Length - 1; while (counter <= maxCount) { Console.WriteLine($"{result} ≡ {a[counter]} (mod {n[counter]})"); counter++; } } } public static class ChineseRemainderTheorem { public static int Solve(int[] n, int[] a) { int prod = n.Aggregate(1, (i, j) => i * j); int p; int sm = 0; for (int i = 0; i < n.Length; i++) { p = prod / n[i]; sm += a[i] * ModularMultiplicativeInverse(p, n[i]) * p; } return sm % prod; } private static int ModularMultiplicativeInverse(int a, int mod) { int b = a % mod; for (int x = 1; x < mod; x++) { if ((b * x) % mod == 1) { return x; } } return 1; } } }
Rewrite the snippet below in C++ so it works the same as the original Haskell code.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Generate a C++ translation of this Haskell snippet without changing its computational steps.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
#include <iostream> #include <numeric> #include <vector> #include <execution> template<typename _Ty> _Ty mulInv(_Ty a, _Ty b) { _Ty b0 = b; _Ty x0 = 0; _Ty x1 = 1; if (b == 1) { return 1; } while (a > 1) { _Ty q = a / b; _Ty amb = a % b; a = b; b = amb; _Ty xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) { x1 += b0; } return x1; } template<typename _Ty> _Ty chineseRemainder(std::vector<_Ty> n, std::vector<_Ty> a) { _Ty prod = std::reduce(std::execution::seq, n.begin(), n.end(), (_Ty)1, [](_Ty a, _Ty b) { return a * b; }); _Ty sm = 0; for (int i = 0; i < n.size(); i++) { _Ty p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } int main() { vector<int> n = { 3, 5, 7 }; vector<int> a = { 2, 3, 2 }; cout << chineseRemainder(n,a) << endl; return 0; }
Produce a functionally identical Java code for the snippet given in Haskell.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Translate this program into Java but keep the logic exactly as in Haskell.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
import static java.util.Arrays.stream; public class ChineseRemainderTheorem { public static int chineseRemainder(int[] n, int[] a) { int prod = stream(n).reduce(1, (i, j) -> i * j); int p, sm = 0; for (int i = 0; i < n.length; i++) { p = prod / n[i]; sm += a[i] * mulInv(p, n[i]) * p; } return sm % prod; } private static int mulInv(int a, int b) { int b0 = b; int x0 = 0; int x1 = 1; if (b == 1) return 1; while (a > 1) { int q = a / b; int amb = a % b; a = b; b = amb; int xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } public static void main(String[] args) { int[] n = {3, 5, 7}; int[] a = {2, 3, 2}; System.out.println(chineseRemainder(n, a)); } }
Transform the following Haskell implementation into Python, maintaining the same output and logic.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Port the following code from Haskell to Python with equivalent syntax and logic.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
def chinese_remainder(n, a): sum = 0 prod = reduce(lambda a, b: a*b, n) for n_i, a_i in zip(n, a): p = prod / n_i sum += a_i * mul_inv(p, n_i) * p return sum % prod def mul_inv(a, b): b0 = b x0, x1 = 0, 1 if b == 1: return 1 while a > 1: q = a / b a, b = b, a%b x0, x1 = x1 - q * x0, x0 if x1 < 0: x1 += b0 return x1 if __name__ == '__main__': n = [3, 5, 7] a = [2, 3, 2] print chinese_remainder(n, a)
Maintain the same structure and functionality when rewriting this code in VB.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Write the same code in VB as shown below in Haskell.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
Private Function chinese_remainder(n As Variant, a As Variant) As Variant Dim p As Long, prod As Long, tot As Long prod = 1: tot = 0 For i = 1 To UBound(n) prod = prod * n(i) Next i Dim m As Variant For i = 1 To UBound(n) p = prod / n(i) m = mul_inv(p, n(i)) If WorksheetFunction.IsText(m) Then chinese_remainder = "fail" Exit Function End If tot = tot + a(i) * m * p Next i chinese_remainder = tot Mod prod End Function Public Sub re() Debug.Print chinese_remainder([{3,5,7}], [{2,3,2}]) Debug.Print chinese_remainder([{11,12,13}], [{10,4,12}]) Debug.Print chinese_remainder([{11,22,19}], [{10,4,9}]) Debug.Print chinese_remainder([{100,23}], [{19,0}]) End Sub
Change the following Haskell code into Go without altering its purpose.
import Control.Monad (zipWithM) egcd :: Int -> Int -> (Int, Int) egcd _ 0 = (1, 0) egcd a b = (t, s - q * t) where (s, t) = egcd b r (q, r) = a `quotRem` b modInv :: Int -> Int -> Either String Int modInv a b = case egcd a b of (x, y) | a * x + b * y == 1 -> Right x | otherwise -> Left $ "No modular inverse for " ++ show a ++ " and " ++ show b chineseRemainder :: [Int] -> [Int] -> Either String Int chineseRemainder residues modulii = zipWithM modInv crtModulii modulii >>= (Right . (`mod` modPI) . sum . zipWith (*) crtModulii . zipWith (*) residues) where modPI = product modulii crtModulii = (modPI `div`) <$> modulii main :: IO () main = mapM_ (putStrLn . either id show) $ uncurry chineseRemainder <$> [ ([10, 4, 12], [11, 12, 13]) , ([10, 4, 9], [11, 22, 19]) , ([2, 3, 2], [3, 5, 7]) ]
package main import ( "fmt" "math/big" ) var one = big.NewInt(1) func crt(a, n []*big.Int) (*big.Int, error) { p := new(big.Int).Set(n[0]) for _, n1 := range n[1:] { p.Mul(p, n1) } var x, q, s, z big.Int for i, n1 := range n { q.Div(p, n1) z.GCD(nil, &s, n1, &q) if z.Cmp(one) != 0 { return nil, fmt.Errorf("%d not coprime", n1) } x.Add(&x, s.Mul(a[i], s.Mul(&s, &q))) } return x.Mod(&x, p), nil } func main() { n := []*big.Int{ big.NewInt(3), big.NewInt(5), big.NewInt(7), } a := []*big.Int{ big.NewInt(2), big.NewInt(3), big.NewInt(2), } fmt.Println(crt(a, n)) }