Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from Ruby to PHP with equivalent syntax and logic.
require 'flt' include Flt BinNum.Context.precision = 512 def agm(a,g) new_a = BinNum a new_g = BinNum g while new_a - new_g > new_a.class.Context.epsilon do old_g = new_g new_g = (new_a * new_g).sqrt new_a = (old_g + new_a) * 0.5 end new_g end puts agm(1, 1 / BinNum(2).sqrt)
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Translate this program into PHP but keep the logic exactly as in Scala.
fun agm(a: Double, g: Double): Double { var aa = a var gg = g var ta: Double val epsilon = 1.0e-16 while (true) { ta = (aa + gg) / 2.0 if (Math.abs(aa - ta) <= epsilon) return ta gg = Math.sqrt(aa * gg) aa = ta } } fun main(args: Array<String>) { println(agm(1.0, 1.0 / Math.sqrt(2.0))) }
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Maintain the same structure and functionality when rewriting this code in PHP.
fun agm(a: Double, g: Double): Double { var aa = a var gg = g var ta: Double val epsilon = 1.0e-16 while (true) { ta = (aa + gg) / 2.0 if (Math.abs(aa - ta) <= epsilon) return ta gg = Math.sqrt(aa * gg) aa = ta } } fun main(args: Array<String>) { println(agm(1.0, 1.0 / Math.sqrt(2.0))) }
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Can you help me rewrite this code in PHP instead of Swift, keeping it the same logically?
import Darwin enum AGRError : Error { case undefined } func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double { var a = a var g = g var a1: Double = 0 var g1: Double = 0 guard a * g >= 0 else { throw AGRError.undefined } while abs(a - g) > iota { a1 = (a + g) / 2 g1 = sqrt(a * g) a = a1 g = g1 } return a } do { try print(agm(1, 1 / sqrt(2))) } catch { print("agr is undefined when a * g < 0") }
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Translate the given Swift code snippet into PHP without altering its behavior.
import Darwin enum AGRError : Error { case undefined } func agm(_ a: Double, _ g: Double, _ iota: Double = 1e-8) throws -> Double { var a = a var g = g var a1: Double = 0 var g1: Double = 0 guard a * g >= 0 else { throw AGRError.undefined } while abs(a - g) > iota { a1 = (a + g) / 2 g1 = sqrt(a * g) a = a1 g = g1 } return a } do { try print(agm(1, 1 / sqrt(2))) } catch { print("agr is undefined when a * g < 0") }
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Transform the following Tcl implementation into PHP, maintaining the same output and logic.
proc agm {a b} { set old_b [expr {$b<0?inf:-inf}] while {$a != $b && $b != $old_b} { set old_b $b lassign [list [expr {0.5*($a+$b)}] [expr {sqrt($a*$b)}]] a b } return $a } puts [agm 1 [expr 1/sqrt(2)]]
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Write the same code in PHP as shown below in Tcl.
proc agm {a b} { set old_b [expr {$b<0?inf:-inf}] while {$a != $b && $b != $old_b} { set old_b $b lassign [list [expr {0.5*($a+$b)}] [expr {sqrt($a*$b)}]] a b } return $a } puts [agm 1 [expr 1/sqrt(2)]]
define('PRECISION', 13); function agm($a0, $g0, $tolerance = 1e-10) { $limit = number_format($tolerance, PRECISION, '.', ''); $an = $a0; $gn = $g0; do { list($an, $gn) = array( bcdiv(bcadd($an, $gn), 2), bcsqrt(bcmul($an, $gn)), ); } while (bccomp(bcsub($an, $gn), $limit) > 0); return $an; } bcscale(PRECISION); echo agm(1, 1 / bcsqrt(2));
Port the following code from C to Rust with equivalent syntax and logic.
#include<math.h> #include<stdio.h> #include<stdlib.h> double agm( double a, double g ) { double iota = 1.0E-16; double a1, g1; if( a*g < 0.0 ) { printf( "arithmetic-geometric mean undefined when x*y<0\n" ); exit(1); } while( fabs(a-g)>iota ) { a1 = (a + g) / 2.0; g1 = sqrt(a * g); a = a1; g = g1; } return a; } int main( void ) { double x, y; printf( "Enter two numbers: " ); scanf( "%lf%lf", &x, &y ); printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) ); return 0; }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Port the provided C++ code into Rust while preserving the original functionality.
#include "gmp.h" void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); } int main (void) { mpf_set_default_prec (65568); mpf_t x0, y0, resA, resB; mpf_init_set_ui (y0, 1); mpf_init_set_d (x0, 0.5); mpf_sqrt (x0, x0); mpf_init (resA); mpf_init (resB); for(int i=0; i<7; i++){ agm(x0, y0, resA, resB); agm(resA, resB, x0, y0); } gmp_printf ("%.20000Ff\n", x0); gmp_printf ("%.20000Ff\n\n", y0); return 0; }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Port the following code from C# to Rust with equivalent syntax and logic.
namespace RosettaCode.ArithmeticGeometricMean { using System; using System.Collections.Generic; using System.Globalization; internal static class Program { private static double ArithmeticGeometricMean(double number, double otherNumber, IEqualityComparer<double> comparer) { return comparer.Equals(number, otherNumber) ? number : ArithmeticGeometricMean( ArithmeticMean(number, otherNumber), GeometricMean(number, otherNumber), comparer); } private static double ArithmeticMean(double number, double otherNumber) { return 0.5 * (number + otherNumber); } private static double GeometricMean(double number, double otherNumber) { return Math.Sqrt(number * otherNumber); } private static void Main() { Console.WriteLine( ArithmeticGeometricMean(1, 0.5 * Math.Sqrt(2), new RelativeDifferenceComparer(1e-5)). ToString(CultureInfo.InvariantCulture)); } private class RelativeDifferenceComparer : IEqualityComparer<double> { private readonly double _maximumRelativeDifference; internal RelativeDifferenceComparer(double maximumRelativeDifference) { _maximumRelativeDifference = maximumRelativeDifference; } public bool Equals(double number, double otherNumber) { return RelativeDifference(number, otherNumber) <= _maximumRelativeDifference; } public int GetHashCode(double number) { return number.GetHashCode(); } private static double RelativeDifference(double number, double otherNumber) { return AbsoluteDifference(number, otherNumber) / Norm(number, otherNumber); } private static double AbsoluteDifference(double number, double otherNumber) { return Math.Abs(number - otherNumber); } private static double Norm(double number, double otherNumber) { return 0.5 * (Math.Abs(number) + Math.Abs(otherNumber)); } } } }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Generate an equivalent Rust version of this C# code.
namespace RosettaCode.ArithmeticGeometricMean { using System; using System.Collections.Generic; using System.Globalization; internal static class Program { private static double ArithmeticGeometricMean(double number, double otherNumber, IEqualityComparer<double> comparer) { return comparer.Equals(number, otherNumber) ? number : ArithmeticGeometricMean( ArithmeticMean(number, otherNumber), GeometricMean(number, otherNumber), comparer); } private static double ArithmeticMean(double number, double otherNumber) { return 0.5 * (number + otherNumber); } private static double GeometricMean(double number, double otherNumber) { return Math.Sqrt(number * otherNumber); } private static void Main() { Console.WriteLine( ArithmeticGeometricMean(1, 0.5 * Math.Sqrt(2), new RelativeDifferenceComparer(1e-5)). ToString(CultureInfo.InvariantCulture)); } private class RelativeDifferenceComparer : IEqualityComparer<double> { private readonly double _maximumRelativeDifference; internal RelativeDifferenceComparer(double maximumRelativeDifference) { _maximumRelativeDifference = maximumRelativeDifference; } public bool Equals(double number, double otherNumber) { return RelativeDifference(number, otherNumber) <= _maximumRelativeDifference; } public int GetHashCode(double number) { return number.GetHashCode(); } private static double RelativeDifference(double number, double otherNumber) { return AbsoluteDifference(number, otherNumber) / Norm(number, otherNumber); } private static double AbsoluteDifference(double number, double otherNumber) { return Math.Abs(number - otherNumber); } private static double Norm(double number, double otherNumber) { return 0.5 * (Math.Abs(number) + Math.Abs(otherNumber)); } } } }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Produce a functionally identical Rust code for the snippet given in Go.
package main import ( "fmt" "math" ) const ε = 1e-14 func agm(a, g float64) float64 { for math.Abs(a-g) > math.Abs(a)*ε { a, g = (a+g)*.5, math.Sqrt(a*g) } return a } func main() { fmt.Println(agm(1, 1/math.Sqrt2)) }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Port the following code from Rust to Python with equivalent syntax and logic.
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
from math import sqrt def agm(a0, g0, tolerance=1e-10): an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0) while abs(an - gn) > tolerance: an, gn = (an + gn) / 2.0, sqrt(an * gn) return an print agm(1, 1 / sqrt(2))
Rewrite the snippet below in Python so it works the same as the original Rust code.
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
from math import sqrt def agm(a0, g0, tolerance=1e-10): an, gn = (a0 + g0) / 2.0, sqrt(a0 * g0) while abs(an - gn) > tolerance: an, gn = (an + gn) / 2.0, sqrt(an * gn) return an print agm(1, 1 / sqrt(2))
Change the following C code into Rust without altering its purpose.
#include<math.h> #include<stdio.h> #include<stdlib.h> double agm( double a, double g ) { double iota = 1.0E-16; double a1, g1; if( a*g < 0.0 ) { printf( "arithmetic-geometric mean undefined when x*y<0\n" ); exit(1); } while( fabs(a-g)>iota ) { a1 = (a + g) / 2.0; g1 = sqrt(a * g); a = a1; g = g1; } return a; } int main( void ) { double x, y; printf( "Enter two numbers: " ); scanf( "%lf%lf", &x, &y ); printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) ); return 0; }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Translate the given Java code snippet into Rust without altering its behavior.
public class ArithmeticGeometricMean { public static double agm(double a, double g) { double a1 = a; double g1 = g; while (Math.abs(a1 - g1) >= 1.0e-14) { double arith = (a1 + g1) / 2.0; double geom = Math.sqrt(a1 * g1); a1 = arith; g1 = geom; } return a1; } public static void main(String[] args) { System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0))); } }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Write the same algorithm in Rust as shown in this Go implementation.
package main import ( "fmt" "math" ) const ε = 1e-14 func agm(a, g float64) float64 { for math.Abs(a-g) > math.Abs(a)*ε { a, g = (a+g)*.5, math.Sqrt(a*g) } return a } func main() { fmt.Println(agm(1, 1/math.Sqrt2)) }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Write a version of this Rust function in VB with identical behavior.
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double Do While Abs(a - g) > tolerance tmp = a a = (a + g) / 2 g = Sqr(tmp * g) Debug.Print a Loop agm = a End Function Public Sub main() Debug.Print agm(1, 1 / Sqr(2)) End Sub
Write the same code in Rust as shown below in C++.
#include "gmp.h" void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { mpf_add (out1, in1, in2); mpf_div_ui (out1, out1, 2); mpf_mul (out2, in1, in2); mpf_sqrt (out2, out2); } int main (void) { mpf_set_default_prec (65568); mpf_t x0, y0, resA, resB; mpf_init_set_ui (y0, 1); mpf_init_set_d (x0, 0.5); mpf_sqrt (x0, x0); mpf_init (resA); mpf_init (resB); for(int i=0; i<7; i++){ agm(x0, y0, resA, resB); agm(resA, resB, x0, y0); } gmp_printf ("%.20000Ff\n", x0); gmp_printf ("%.20000Ff\n\n", y0); return 0; }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Write the same algorithm in Rust as shown in this Java implementation.
public class ArithmeticGeometricMean { public static double agm(double a, double g) { double a1 = a; double g1 = g; while (Math.abs(a1 - g1) >= 1.0e-14) { double arith = (a1 + g1) / 2.0; double geom = Math.sqrt(a1 * g1); a1 = arith; g1 = geom; } return a1; } public static void main(String[] args) { System.out.println(agm(1.0, 1.0 / Math.sqrt(2.0))); } }
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Write the same algorithm in VB as shown in this Rust implementation.
fn main () { let mut args = std::env::args(); let x = args.nth(1).expect("First argument not specified.").parse::<f32>().unwrap(); let y = args.next().expect("Second argument not specified.").parse::<f32>().unwrap(); let result = agm(x,y); println!("The arithmetic-geometric mean is {}", result); } fn agm (x: f32, y: f32) -> f32 { let e: f32 = 0.000001; let mut a = x; let mut g = y; let mut a1: f32; let mut g1: f32; if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } else { loop { a1 = (a + g) / 2.; g1 = (a * g).sqrt(); a = a1; g = g1; if (a - g).abs() < e { return a; } } } }
Private Function agm(a As Double, g As Double, Optional tolerance As Double = 0.000000000000001) As Double Do While Abs(a - g) > tolerance tmp = a a = (a + g) / 2 g = Sqr(tmp * g) Debug.Print a Loop agm = a End Function Public Sub main() Debug.Print agm(1, 1 / Sqr(2)) End Sub
Port the provided Ada code into C# while preserving the original functionality.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 Ada snippet to C# and keep its semantics consistent.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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; } } }
Generate an equivalent C version of this Ada code.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
#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 Ada code snippet into C without altering its behavior.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
#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 Ada to C++ with equivalent syntax and logic.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
#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 C++ instead of Ada, keeping it the same logically?
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
#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 Ada to Go, ensuring the logic remains intact.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 programming language of this snippet from Ada to Go without modifying what it does.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 Java.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 the given Ada code snippet into Java without altering its behavior.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 Ada implementation into Python, maintaining the same output and logic.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 programming language of this snippet from Ada to Python without modifying what it does.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 Ada implementation.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 Ada snippet.
with Ada.Text_IO, Mod_Inv; procedure Chin_Rema is N: array(Positive range <>) of Positive := (3, 5, 7); A: array(Positive range <>) of Positive := (2, 3, 2); Tmp: Positive; Prod: Positive := 1; Sum: Natural := 0; begin for I in N'Range loop Prod := Prod * N(I); end loop; for I in A'Range loop Tmp := Prod / N(I); Sum := Sum + A(I) * Mod_Inv.Inverse(Tmp, N(I)) * Tmp; end loop; Ada.Text_IO.Put_Line(Integer'Image(Sum mod Prod)); end Chin_Rema;
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 C.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
#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 Arturo snippet without changing its computational steps.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
#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; }
Convert this Arturo block to C#, preserving its control flow and logic.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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#.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 this program in C++ while keeping its functionality equivalent to the Arturo version.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
#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 this program in C++ while keeping its functionality equivalent to the Arturo version.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
#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 this program in Java while keeping its functionality equivalent to the Arturo version.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 programming language of this snippet from Arturo to Java without modifying what it does.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 Arturo block to Python, preserving its control flow and logic.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 an equivalent Python version of this Arturo code.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 code in VB as shown below in Arturo.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 Arturo implementation into VB, maintaining the same output and logic.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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
Produce a language-to-language conversion: from Arturo to Go, same semantics.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 Arturo function in Go with identical behavior.
mulInv: function [a0, b0][ [a b x0]: @[a0 b0 0] result: 1 if b = 1 -> return result while [a > 1][ q: a / b a: a % b tmp: a a: b b: tmp result: result - q * x0 tmp: x0 x0: result result: tmp ] if result < 0 -> result: result + b0 return result ] chineseRemainder: function [N, A][ prod: 1 s: 0 loop N 'x -> prod: prod * x loop.with:'i N 'x [ p: prod / x s: s + (mulInv p x) * p * A\[i] ] return s % prod ] print chineseRemainder [3 5 7] [2 3 2]
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 the same code in C as shown below in AWK.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
#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 AWK to C with equivalent syntax and logic.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
#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; }
Keep all operations the same but rewrite the snippet in C#.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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; } } }
Transform the following AWK implementation into C#, maintaining the same output and logic.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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; } } }
Translate the given AWK code snippet into C++ without altering its behavior.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
#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 AWK function in C++ with identical behavior.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
#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 the same algorithm in Java as shown in this AWK implementation.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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)); } }
Port the following code from AWK to Java with equivalent syntax and logic.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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 Python so it works the same as the original AWK code.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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 an equivalent Python version of this AWK code.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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 a version of this AWK function in VB with identical behavior.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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 VB while keeping its functionality equivalent to the AWK version.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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
Can you help me rewrite this code in Go instead of AWK, keeping it the same logically?
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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 AWK implementation into Go, maintaining the same output and logic.
BEGIN { len = split("3 5 7", n) len = split("2 3 2", a) printf("%d\n", chineseremainder(n, a, len)) } function chineseremainder(n, a, len, p, i, prod, sum) { prod = 1 sum = 0 for (i = 1; i <= len; i++) prod *= n[i] for (i = 1; i <= len; i++) { p = prod / n[i] sum += a[i] * mulinv(p, n[i]) * p } return sum % prod } function mulinv(a, b, b0, t, q, x0, x1) { b0 = b x0 = 0 x1 = 1 if (b == 1) return 1 while (a > 1) { q = int(a / b) t = b b = a % b a = t t = x0 x0 = x1 - q * x0 x1 = t } if (x1 < 0) x1 += b0 return x1 }
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)) }
Rewrite this program in C while keeping its functionality equivalent to the Common_Lisp version.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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; }
Transform the following Common_Lisp implementation into C, maintaining the same output and logic.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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; }
Write a version of this Common_Lisp function in C# with identical behavior.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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; } } }
Preserve the algorithm and functionality while converting the code from Common_Lisp to C#.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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++.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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; }
Change the programming language of this snippet from Common_Lisp to C++ without modifying what it does.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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; }
Keep all operations the same but rewrite the snippet in Java.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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 Common_Lisp to Java, same semantics.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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 Common_Lisp block to Python, preserving its control flow and logic.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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 Common_Lisp code snippet into VB without altering its behavior.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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 Common_Lisp code into VB without altering its purpose.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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
Keep all operations the same but rewrite the snippet in Go.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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 Common_Lisp to Go.
(ns test-p.core (:require [clojure.math.numeric-tower :as math])) (defn extended-gcd "The extended Euclidean algorithm Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs. " [a b] (cond (zero? a) [(math/abs b) 0 1] (zero? b) [(math/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (math/abs b) r0 (math/abs a)] (if (zero? r) [r0 s0 t0] (let [q (quot r0 r)] (recur (- s0 (* q s)) s (- t0 (* q t)) t (- r0 (* q r)) r)))))) (defn chinese_remainder " Main routine to return the chinese remainder " [n a] (let [prod (apply * n) reducer (fn [sum [n_i a_i]] (let [p (quot prod n_i) egcd (extended-gcd p n_i) inv_p (second egcd)] (+ sum (* a_i inv_p p)))) sum-prod (reduce reducer 0 (map vector n a))] (mod sum-prod prod))) (def n [3 5 7]) (def a [2 3 2]) (println (chinese_remainder 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)) }
Please provide an equivalent version of this D code in C.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
#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 std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
#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 D.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 D to C# with equivalent syntax and logic.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 D snippet.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
#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 C++ so it works the same as the original D code.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
#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 D code snippet into Java without altering its behavior.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 Java.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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)); } }
Maintain the same structure and functionality when rewriting this code in Python.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 an equivalent Python version of this D code.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 a version of this D function in VB with identical behavior.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 a version of this D function in VB with identical behavior.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 D to Go.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 an equivalent Go version of this D code.
import std.stdio, std.algorithm; T chineseRemainder(T)(in T[] n, in T[] a) pure nothrow @safe @nogc in { assert(n.length == a.length); } body { static T mulInv(T)(T a, T b) pure nothrow @safe @nogc { auto b0 = b; T x0 = 0, x1 = 1; if (b == 1) return T(1); while (a > 1) { immutable q = a / b; immutable amb = a % b; a = b; b = amb; immutable xqx = x1 - q * x0; x1 = x0; x0 = xqx; } if (x1 < 0) x1 += b0; return x1; } immutable prod = reduce!q{a * b}(T(1), n); T p = 1, sm = 0; foreach (immutable i, immutable ni; n) { p = prod / ni; sm += a[i] * mulInv(p, ni) * p; } return sm % prod; } void main() { immutable n = [3, 5, 7], a = [2, 3, 2]; chineseRemainder(n, a).writeln; }
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 Delphi block to C, preserving its control flow and logic.
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.
#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; }
Change the following Delphi code into C without altering its purpose.
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.
#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; }
Convert this Delphi snippet to C# 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.
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 the same algorithm in C# 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.
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 the same code in C++ as shown below in Delphi.
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.
#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 C++ code for the snippet given in Delphi.
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.
#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; }
Maintain the same structure and functionality when rewriting this code in Java.
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.
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 Delphi function in Java with identical behavior.
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.
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 Delphi block to Python, preserving its control flow and logic.
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.
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 Python 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.
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)