Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Maintain the same structure and functionality when rewriting this code in C#. |
niner = '25 15 -5' ,
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42,
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit
Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat
do r=1 for ord
do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end
if r=c then !.r.r=sqrt(!.r.r-d)
else !.r.c=1/!.c.c*(a.r.c-d)
end
end
call tell 'Cholesky factor',,!.,'-'
return
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'
dPlaces= 5
width =10
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width+1)*w)%ord, sep)
say
do row=1 for ord; z=''
do col=1 for ord; n=n+1
a.row.col=word(x,n)
if col<=row then !.row.col=a.row.col
z=z right( format(a.row.col,, dPlaces) / 1, width)
end
say z
end
return
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end
numeric digits d; return (g/1)i
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
}
|
Change the following REXX code into C++ without altering its purpose. |
niner = '25 15 -5' ,
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42,
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit
Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat
do r=1 for ord
do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end
if r=c then !.r.r=sqrt(!.r.r-d)
else !.r.c=1/!.c.c*(a.r.c-d)
end
end
call tell 'Cholesky factor',,!.,'-'
return
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'
dPlaces= 5
width =10
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width+1)*w)%ord, sep)
say
do row=1 for ord; z=''
do col=1 for ord; n=n+1
a.row.col=word(x,n)
if col<=row then !.row.col=a.row.col
z=z right( format(a.row.col,, dPlaces) / 1, width)
end
say z
end
return
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end
numeric digits d; return (g/1)i
| #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
}
|
Write the same code in Java as shown below in REXX. |
niner = '25 15 -5' ,
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42,
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit
Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat
do r=1 for ord
do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end
if r=c then !.r.r=sqrt(!.r.r-d)
else !.r.c=1/!.c.c*(a.r.c-d)
end
end
call tell 'Cholesky factor',,!.,'-'
return
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'
dPlaces= 5
width =10
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width+1)*w)%ord, sep)
say
do row=1 for ord; z=''
do col=1 for ord; n=n+1
a.row.col=word(x,n)
if col<=row then !.row.col=a.row.col
z=z right( format(a.row.col,, dPlaces) / 1, width)
end
say z
end
return
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end
numeric digits d; return (g/1)i
| import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m];
for(int i = 0; i< m;i++){
for(int k = 0; k < (i+1); k++){
double sum = 0;
for(int j = 0; j < k; j++){
sum += l[i][j] * l[k][j];
}
l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
(1.0 / l[k][k] * (a[i][k] - sum));
}
}
return l;
}
public static void main(String[] args){
double[][] test1 = {{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}};
System.out.println(Arrays.deepToString(chol(test1)));
double[][] test2 = {{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}};
System.out.println(Arrays.deepToString(chol(test2)));
}
}
|
Translate the given REXX code snippet into Python without altering its behavior. |
niner = '25 15 -5' ,
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42,
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit
Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat
do r=1 for ord
do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end
if r=c then !.r.r=sqrt(!.r.r-d)
else !.r.c=1/!.c.c*(a.r.c-d)
end
end
call tell 'Cholesky factor',,!.,'-'
return
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'
dPlaces= 5
width =10
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width+1)*w)%ord, sep)
say
do row=1 for ord; z=''
do col=1 for ord; n=n+1
a.row.col=word(x,n)
if col<=row then !.row.col=a.row.col
z=z right( format(a.row.col,, dPlaces) / 1, width)
end
say z
end
return
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end
numeric digits d; return (g/1)i
| from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == "__main__":
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)
|
Maintain the same structure and functionality when rewriting this code in VB. |
niner = '25 15 -5' ,
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42,
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit
Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat
do r=1 for ord
do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end
if r=c then !.r.r=sqrt(!.r.r-d)
else !.r.c=1/!.c.c*(a.r.c-d)
end
end
call tell 'Cholesky factor',,!.,'-'
return
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'
dPlaces= 5
width =10
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width+1)*w)%ord, sep)
say
do row=1 for ord; z=''
do col=1 for ord; n=n+1
a.row.col=word(x,n)
if col<=row then !.row.col=a.row.col
z=z right( format(a.row.col,, dPlaces) / 1, width)
end
say z
end
return
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end
numeric digits d; return (g/1)i
| Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
Keep all operations the same but rewrite the snippet in Go. |
niner = '25 15 -5' ,
'15 18 0' ,
'-5 0 11'
call Cholesky niner
hexer = 18 22 54 42,
22 70 86 62,
54 86 174 134,
42 62 134 106
call Cholesky hexer
exit
Cholesky: procedure; parse arg mat; say; say; call tell 'input matrix',mat
do r=1 for ord
do c=1 for r; d=0; do i=1 for c-1; d=d+!.r.i*!.c.i; end
if r=c then !.r.r=sqrt(!.r.r-d)
else !.r.c=1/!.c.c*(a.r.c-d)
end
end
call tell 'Cholesky factor',,!.,'-'
return
err: say; say; say '***error***!'; say; say arg(1); say; say; exit 13
tell: parse arg hdr,x,y,sep; n=0; if sep=='' then sep='-'
dPlaces= 5
width =10
if y=='' then !.=0
else do row=1 for ord; do col=1 for ord; x=x !.row.col; end; end
w=words(x)
do ord=1 until ord**2>=w; end
say
if ord**2\==w then call err "matrix elements don't form a square matrix."
say center(hdr, ((width+1)*w)%ord, sep)
say
do row=1 for ord; z=''
do col=1 for ord; n=n+1
a.row.col=word(x,n)
if col<=row then !.row.col=a.row.col
z=z right( format(a.row.col,, dPlaces) / 1, width)
end
say z
end
return
sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); i=''; m.=9
numeric digits 9; numeric form; h=d+6; if x<0 then do; x=-x; i='i'; end
parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_%2
do j=0 while h>9; m.j=h; h=h%2+1; end
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end
numeric digits d; return (g/1)i
| package main
import (
"fmt"
"math"
)
type symmetric struct {
order int
ele []float64
}
type lower struct {
order int
ele []float64
}
func (s *symmetric) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range s.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
fmt.Printf(eleFmt, s.ele[j])
col++
}
fmt.Println()
row++
diag += row
}
}
}
func (l *lower) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range l.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j := row; j < l.order; j++ {
fmt.Printf(eleFmt, 0.)
}
fmt.Println()
row++
diag += row
}
}
}
func (a *symmetric) choleskyLower() *lower {
l := &lower{a.order, make([]float64, len(a.ele))}
row, col := 1, 1
dr := 0
dc := 0
for i, e := range a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
ci, cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.Sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
func main() {
demo(&symmetric{3, []float64{
25,
15, 18,
-5, 0, 11}})
demo(&symmetric{4, []float64{
18,
22, 70,
54, 86, 174,
42, 62, 134, 106}})
}
func demo(a *symmetric) {
fmt.Println("A:")
a.print()
fmt.Println("L:")
a.choleskyLower().print()
}
|
Translate this program into C but keep the logic exactly as in Ruby. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
void show_matrix(double *A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i * n + j]);
printf("\n");
}
}
int main() {
int n = 3;
double m1[] = {25, 15, -5,
15, 18, 0,
-5, 0, 11};
double *c1 = cholesky(m1, n);
show_matrix(c1, n);
printf("\n");
free(c1);
n = 4;
double m2[] = {18, 22, 54, 42,
22, 70, 86, 62,
54, 86, 174, 134,
42, 62, 134, 106};
double *c2 = cholesky(m2, n);
show_matrix(c2, n);
free(c2);
return 0;
}
|
Change the programming language of this snippet from Ruby to C# without modifying what it does. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Ruby to C++. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
}
|
Produce a language-to-language conversion: from Ruby to Java, same semantics. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m];
for(int i = 0; i< m;i++){
for(int k = 0; k < (i+1); k++){
double sum = 0;
for(int j = 0; j < k; j++){
sum += l[i][j] * l[k][j];
}
l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
(1.0 / l[k][k] * (a[i][k] - sum));
}
}
return l;
}
public static void main(String[] args){
double[][] test1 = {{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}};
System.out.println(Arrays.deepToString(chol(test1)));
double[][] test2 = {{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}};
System.out.println(Arrays.deepToString(chol(test2)));
}
}
|
Convert the following code from Ruby to Python, ensuring the logic remains intact. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == "__main__":
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)
|
Maintain the same structure and functionality when rewriting this code in VB. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
Write the same algorithm in Go as shown in this Ruby implementation. | require 'matrix'
class Matrix
def cholesky_factor
raise ArgumentError, "must provide symmetric matrix" unless symmetric?
l = Array.new(row_size) {Array.new(row_size, 0)}
(0 ... row_size).each do |k|
(0 ... row_size).each do |i|
if i == k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[k][j] ** 2}
val = Math.sqrt(self[k,k] - sum)
l[k][k] = val
elsif i > k
sum = (0 .. k-1).inject(0.0) {|sum, j| sum + l[i][j] * l[k][j]}
val = (self[k,i] - sum) / l[k][k]
l[i][k] = val
end
end
end
Matrix[*l]
end
end
puts Matrix[[25,15,-5],[15,18,0],[-5,0,11]].cholesky_factor
puts Matrix[[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]].cholesky_factor
| package main
import (
"fmt"
"math"
)
type symmetric struct {
order int
ele []float64
}
type lower struct {
order int
ele []float64
}
func (s *symmetric) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range s.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
fmt.Printf(eleFmt, s.ele[j])
col++
}
fmt.Println()
row++
diag += row
}
}
}
func (l *lower) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range l.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j := row; j < l.order; j++ {
fmt.Printf(eleFmt, 0.)
}
fmt.Println()
row++
diag += row
}
}
}
func (a *symmetric) choleskyLower() *lower {
l := &lower{a.order, make([]float64, len(a.ele))}
row, col := 1, 1
dr := 0
dc := 0
for i, e := range a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
ci, cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.Sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
func main() {
demo(&symmetric{3, []float64{
25,
15, 18,
-5, 0, 11}})
demo(&symmetric{4, []float64{
18,
22, 70,
54, 86, 174,
42, 62, 134, 106}})
}
func demo(a *symmetric) {
fmt.Println("A:")
a.print()
fmt.Println("L:")
a.choleskyLower().print()
}
|
Convert this Scala snippet to C and keep its semantics consistent. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
void show_matrix(double *A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i * n + j]);
printf("\n");
}
}
int main() {
int n = 3;
double m1[] = {25, 15, -5,
15, 18, 0,
-5, 0, 11};
double *c1 = cholesky(m1, n);
show_matrix(c1, n);
printf("\n");
free(c1);
n = 4;
double m2[] = {18, 22, 54, 42,
22, 70, 86, 62,
54, 86, 174, 134,
42, 62, 134, 106};
double *c2 = cholesky(m2, n);
show_matrix(c2, n);
free(c2);
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Scala version. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
}
|
Change the following Scala code into C++ without altering its purpose. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
}
|
Change the programming language of this snippet from Scala to Java without modifying what it does. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m];
for(int i = 0; i< m;i++){
for(int k = 0; k < (i+1); k++){
double sum = 0;
for(int j = 0; j < k; j++){
sum += l[i][j] * l[k][j];
}
l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
(1.0 / l[k][k] * (a[i][k] - sum));
}
}
return l;
}
public static void main(String[] args){
double[][] test1 = {{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}};
System.out.println(Arrays.deepToString(chol(test1)));
double[][] test2 = {{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}};
System.out.println(Arrays.deepToString(chol(test2)));
}
}
|
Write the same code in Python as shown below in Scala. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == "__main__":
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)
|
Generate a VB translation of this Scala snippet without changing its computational steps. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
Write a version of this Scala function in Go with identical behavior. |
fun cholesky(a: DoubleArray): DoubleArray {
val n = Math.sqrt(a.size.toDouble()).toInt()
val l = DoubleArray(a.size)
var s: Double
for (i in 0 until n)
for (j in 0 .. i) {
s = 0.0
for (k in 0 until j) s += l[i * n + k] * l[j * n + k]
l[i * n + j] = when {
(i == j) -> Math.sqrt(a[i * n + i] - s)
else -> 1.0 / l[j * n + j] * (a[i * n + j] - s)
}
}
return l
}
fun showMatrix(a: DoubleArray) {
val n = Math.sqrt(a.size.toDouble()).toInt()
for (i in 0 until n) {
for (j in 0 until n) print("%8.5f ".format(a[i * n + j]))
println()
}
}
fun main(args: Array<String>) {
val m1 = doubleArrayOf(25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0)
val c1 = cholesky(m1)
showMatrix(c1)
println()
val m2 = doubleArrayOf(18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0)
val c2 = cholesky(m2)
showMatrix(c2)
}
| package main
import (
"fmt"
"math"
)
type symmetric struct {
order int
ele []float64
}
type lower struct {
order int
ele []float64
}
func (s *symmetric) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range s.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
fmt.Printf(eleFmt, s.ele[j])
col++
}
fmt.Println()
row++
diag += row
}
}
}
func (l *lower) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range l.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j := row; j < l.order; j++ {
fmt.Printf(eleFmt, 0.)
}
fmt.Println()
row++
diag += row
}
}
}
func (a *symmetric) choleskyLower() *lower {
l := &lower{a.order, make([]float64, len(a.ele))}
row, col := 1, 1
dr := 0
dc := 0
for i, e := range a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
ci, cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.Sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
func main() {
demo(&symmetric{3, []float64{
25,
15, 18,
-5, 0, 11}})
demo(&symmetric{4, []float64{
18,
22, 70,
54, 86, 174,
42, 62, 134, 106}})
}
func demo(a *symmetric) {
fmt.Println("A:")
a.print()
fmt.Println("L:")
a.choleskyLower().print()
}
|
Translate the given Swift code snippet into C without altering its behavior. | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
void show_matrix(double *A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i * n + j]);
printf("\n");
}
}
int main() {
int n = 3;
double m1[] = {25, 15, -5,
15, 18, 0,
-5, 0, 11};
double *c1 = cholesky(m1, n);
show_matrix(c1, n);
printf("\n");
free(c1);
n = 4;
double m2[] = {18, 22, 54, 42,
22, 70, 86, 62,
54, 86, 174, 134,
42, 62, 134, 106};
double *c2 = cholesky(m2, n);
show_matrix(c2, n);
free(c2);
return 0;
}
|
Can you help me rewrite this code in C# instead of Swift, keeping it the same logically? | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
}
|
Produce a language-to-language conversion: from Swift to C++, same semantics. | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
}
|
Produce a language-to-language conversion: from Swift to Java, same semantics. | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m];
for(int i = 0; i< m;i++){
for(int k = 0; k < (i+1); k++){
double sum = 0;
for(int j = 0; j < k; j++){
sum += l[i][j] * l[k][j];
}
l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
(1.0 / l[k][k] * (a[i][k] - sum));
}
}
return l;
}
public static void main(String[] args){
double[][] test1 = {{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}};
System.out.println(Arrays.deepToString(chol(test1)));
double[][] test2 = {{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}};
System.out.println(Arrays.deepToString(chol(test2)));
}
}
|
Convert this Swift snippet to Python and keep its semantics consistent. | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == "__main__":
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)
|
Convert this Swift block to VB, preserving its control flow and logic. | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
Transform the following Swift implementation into Go, maintaining the same output and logic. | func cholesky(matrix: [Double], n: Int) -> [Double] {
var res = [Double](repeating: 0, count: matrix.count)
for i in 0..<n {
for j in 0..<i+1 {
var s = 0.0
for k in 0..<j {
s += res[i * n + k] * res[j * n + k]
}
if i == j {
res[i * n + j] = (matrix[i * n + i] - s).squareRoot()
} else {
res[i * n + j] = (1.0 / res[j * n + j] * (matrix[i * n + j] - s))
}
}
}
return res
}
func printMatrix(_ matrix: [Double], n: Int) {
for i in 0..<n {
for j in 0..<n {
print(matrix[i * n + j], terminator: " ")
}
print()
}
}
let res1 = cholesky(
matrix: [25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0],
n: 3
)
let res2 = cholesky(
matrix: [18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0],
n: 4
)
printMatrix(res1, n: 3)
print()
printMatrix(res2, n: 4)
| package main
import (
"fmt"
"math"
)
type symmetric struct {
order int
ele []float64
}
type lower struct {
order int
ele []float64
}
func (s *symmetric) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range s.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
fmt.Printf(eleFmt, s.ele[j])
col++
}
fmt.Println()
row++
diag += row
}
}
}
func (l *lower) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range l.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j := row; j < l.order; j++ {
fmt.Printf(eleFmt, 0.)
}
fmt.Println()
row++
diag += row
}
}
}
func (a *symmetric) choleskyLower() *lower {
l := &lower{a.order, make([]float64, len(a.ele))}
row, col := 1, 1
dr := 0
dc := 0
for i, e := range a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
ci, cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.Sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
func main() {
demo(&symmetric{3, []float64{
25,
15, 18,
-5, 0, 11}})
demo(&symmetric{4, []float64{
18,
22, 70,
54, 86, 174,
42, 62, 134, 106}})
}
func demo(a *symmetric) {
fmt.Println("A:")
a.print()
fmt.Println("L:")
a.choleskyLower().print()
}
|
Rewrite the snippet below in C so it works the same as the original Tcl code. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
void show_matrix(double *A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i * n + j]);
printf("\n");
}
}
int main() {
int n = 3;
double m1[] = {25, 15, -5,
15, 18, 0,
-5, 0, 11};
double *c1 = cholesky(m1, n);
show_matrix(c1, n);
printf("\n");
free(c1);
n = 4;
double m2[] = {18, 22, 54, 42,
22, 70, 86, 62,
54, 86, 174, 134,
42, 62, 134, 106};
double *c2 = cholesky(m2, n);
show_matrix(c2, n);
free(c2);
return 0;
}
|
Write a version of this Tcl function in C# with identical behavior. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
}
|
Translate the given Tcl code snippet into C++ without altering its behavior. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
}
|
Convert this Tcl block to Java, preserving its control flow and logic. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m];
for(int i = 0; i< m;i++){
for(int k = 0; k < (i+1); k++){
double sum = 0;
for(int j = 0; j < k; j++){
sum += l[i][j] * l[k][j];
}
l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
(1.0 / l[k][k] * (a[i][k] - sum));
}
}
return l;
}
public static void main(String[] args){
double[][] test1 = {{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}};
System.out.println(Arrays.deepToString(chol(test1)));
double[][] test2 = {{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}};
System.out.println(Arrays.deepToString(chol(test2)));
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == "__main__":
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)
|
Convert the following code from Tcl to VB, ensuring the logic remains intact. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
Port the provided Tcl code into Go while preserving the original functionality. | proc cholesky a {
set m [llength $a]
set n [llength [lindex $a 0]]
set l [lrepeat $m [lrepeat $n 0.0]]
for {set i 0} {$i < $m} {incr i} {
for {set k 0} {$k < $i+1} {incr k} {
set sum 0.0
for {set j 0} {$j < $k} {incr j} {
set sum [expr {$sum + [lindex $l $i $j] * [lindex $l $k $j]}]
}
lset l $i $k [expr {
$i == $k
? sqrt([lindex $a $i $i] - $sum)
: (1.0 / [lindex $l $k $k] * ([lindex $a $i $k] - $sum))
}]
}
}
return $l
}
| package main
import (
"fmt"
"math"
)
type symmetric struct {
order int
ele []float64
}
type lower struct {
order int
ele []float64
}
func (s *symmetric) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range s.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
fmt.Printf(eleFmt, s.ele[j])
col++
}
fmt.Println()
row++
diag += row
}
}
}
func (l *lower) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range l.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j := row; j < l.order; j++ {
fmt.Printf(eleFmt, 0.)
}
fmt.Println()
row++
diag += row
}
}
}
func (a *symmetric) choleskyLower() *lower {
l := &lower{a.order, make([]float64, len(a.ele))}
row, col := 1, 1
dr := 0
dc := 0
for i, e := range a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
ci, cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.Sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
func main() {
demo(&symmetric{3, []float64{
25,
15, 18,
-5, 0, 11}})
demo(&symmetric{4, []float64{
18,
22, 70,
54, 86, 174,
42, 62, 134, 106}})
}
func demo(a *symmetric) {
fmt.Println("A:")
a.print()
fmt.Println("L:")
a.choleskyLower().print()
}
|
Translate this program into Rust but keep the logic exactly as in C. | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
double *cholesky(double *A, int n) {
double *L = (double*)calloc(n * n, sizeof(double));
if (L == NULL)
exit(EXIT_FAILURE);
for (int i = 0; i < n; i++)
for (int j = 0; j < (i+1); j++) {
double s = 0;
for (int k = 0; k < j; k++)
s += L[i * n + k] * L[j * n + k];
L[i * n + j] = (i == j) ?
sqrt(A[i * n + i] - s) :
(1.0 / L[j * n + j] * (A[i * n + j] - s));
}
return L;
}
void show_matrix(double *A, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
printf("%2.5f ", A[i * n + j]);
printf("\n");
}
}
int main() {
int n = 3;
double m1[] = {25, 15, -5,
15, 18, 0,
-5, 0, 11};
double *c1 = cholesky(m1, n);
show_matrix(c1, n);
printf("\n");
free(c1);
n = 4;
double m2[] = {18, 22, 54, 42,
22, 70, 86, 62,
54, 86, 174, 134,
42, 62, 134, 106};
double *c2 = cholesky(m2, n);
show_matrix(c2, n);
free(c2);
return 0;
}
| fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
|
Please provide an equivalent version of this C# code in Rust. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Cholesky
{
class Program
{
static void Main(string[] args)
{
double[,] test1 = new double[,]
{
{25, 15, -5},
{15, 18, 0},
{-5, 0, 11},
};
double[,] test2 = new double[,]
{
{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106},
};
double[,] chol1 = Cholesky(test1);
double[,] chol2 = Cholesky(test2);
Console.WriteLine("Test 1: ");
Print(test1);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 1: ");
Print(chol1);
Console.WriteLine("");
Console.WriteLine("Test 2: ");
Print(test2);
Console.WriteLine("");
Console.WriteLine("Lower Cholesky 2: ");
Print(chol2);
}
public static void Print(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
StringBuilder sb = new StringBuilder();
for (int r = 0; r < n; r++)
{
string s = "";
for (int c = 0; c < n; c++)
{
s += a[r, c].ToString("f5").PadLeft(9) + ",";
}
sb.AppendLine(s);
}
Console.WriteLine(sb.ToString());
}
public static double[,] Cholesky(double[,] a)
{
int n = (int)Math.Sqrt(a.Length);
double[,] ret = new double[n, n];
for (int r = 0; r < n; r++)
for (int c = 0; c <= r; c++)
{
if (c == r)
{
double sum = 0;
for (int j = 0; j < c; j++)
{
sum += ret[c, j] * ret[c, j];
}
ret[c, c] = Math.Sqrt(a[c, c] - sum);
}
else
{
double sum = 0;
for (int j = 0; j < c; j++)
sum += ret[r, j] * ret[c, j];
ret[r, c] = 1.0 / ret[c, c] * (a[r, c] - sum);
}
}
return ret;
}
}
}
| fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
|
Preserve the algorithm and functionality while converting the code from Java to Rust. | import java.util.Arrays;
public class Cholesky {
public static double[][] chol(double[][] a){
int m = a.length;
double[][] l = new double[m][m];
for(int i = 0; i< m;i++){
for(int k = 0; k < (i+1); k++){
double sum = 0;
for(int j = 0; j < k; j++){
sum += l[i][j] * l[k][j];
}
l[i][k] = (i == k) ? Math.sqrt(a[i][i] - sum) :
(1.0 / l[k][k] * (a[i][k] - sum));
}
}
return l;
}
public static void main(String[] args){
double[][] test1 = {{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}};
System.out.println(Arrays.deepToString(chol(test1)));
double[][] test2 = {{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}};
System.out.println(Arrays.deepToString(chol(test2)));
}
}
| fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
|
Produce a functionally identical Python code for the snippet given in Rust. | fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
| from __future__ import print_function
from pprint import pprint
from math import sqrt
def cholesky(A):
L = [[0.0] * len(A) for _ in xrange(len(A))]
for i in xrange(len(A)):
for j in xrange(i+1):
s = sum(L[i][k] * L[j][k] for k in xrange(j))
L[i][j] = sqrt(A[i][i] - s) if (i == j) else \
(1.0 / L[j][j] * (A[i][j] - s))
return L
if __name__ == "__main__":
m1 = [[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]]
pprint(cholesky(m1))
print()
m2 = [[18, 22, 54, 42],
[22, 70, 86, 62],
[54, 86, 174, 134],
[42, 62, 134, 106]]
pprint(cholesky(m2), width=120)
|
Maintain the same structure and functionality when rewriting this code in VB. | fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
| Function Cholesky(Mat As Range) As Variant
Dim A() As Double, L() As Double, sum As Double, sum2 As Double
Dim m As Byte, i As Byte, j As Byte, k As Byte
If Mat.Rows.Count <> Mat.Columns.Count Then
MsgBox ("Correlation matrix is not square")
Exit Function
End If
m = Mat.Rows.Count
ReDim A(0 To m - 1, 0 To m - 1)
ReDim L(0 To m - 1, 0 To m - 1)
For i = 0 To m - 1
For j = 0 To m - 1
A(i, j) = Mat(i + 1, j + 1).Value2
L(i, j) = 0
Next j
Next i
Select Case m
Case Is = 1
L(0, 0) = Sqr(A(0, 0))
Case Is = 2
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
Case Else
L(0, 0) = Sqr(A(0, 0))
L(1, 0) = A(1, 0) / L(0, 0)
L(1, 1) = Sqr(A(1, 1) - L(1, 0) * L(1, 0))
For i = 2 To m - 1
sum2 = 0
For k = 0 To i - 1
sum = 0
For j = 0 To k
sum = sum + L(i, j) * L(k, j)
Next j
L(i, k) = (A(i, k) - sum) / L(k, k)
sum2 = sum2 + L(i, k) * L(i, k)
Next k
L(i, i) = Sqr(A(i, i) - sum2)
Next i
End Select
Cholesky = L
End Function
|
Ensure the translated Rust code behaves exactly like the original C++ snippet. | #include <cassert>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
template <typename scalar_type> class matrix {
public:
matrix(size_t rows, size_t columns)
: rows_(rows), columns_(columns), elements_(rows * columns) {}
matrix(size_t rows, size_t columns, scalar_type value)
: rows_(rows), columns_(columns), elements_(rows * columns, value) {}
matrix(size_t rows, size_t columns,
const std::initializer_list<std::initializer_list<scalar_type>>& values)
: rows_(rows), columns_(columns), elements_(rows * columns) {
assert(values.size() <= rows_);
size_t i = 0;
for (const auto& row : values) {
assert(row.size() <= columns_);
std::copy(begin(row), end(row), &elements_[i]);
i += columns_;
}
}
size_t rows() const { return rows_; }
size_t columns() const { return columns_; }
const scalar_type& operator()(size_t row, size_t column) const {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
scalar_type& operator()(size_t row, size_t column) {
assert(row < rows_);
assert(column < columns_);
return elements_[row * columns_ + column];
}
private:
size_t rows_;
size_t columns_;
std::vector<scalar_type> elements_;
};
template <typename scalar_type>
void print(std::ostream& out, const matrix<scalar_type>& a) {
size_t rows = a.rows(), columns = a.columns();
out << std::fixed << std::setprecision(5);
for (size_t row = 0; row < rows; ++row) {
for (size_t column = 0; column < columns; ++column) {
if (column > 0)
out << ' ';
out << std::setw(9) << a(row, column);
}
out << '\n';
}
}
template <typename scalar_type>
matrix<scalar_type> cholesky_factor(const matrix<scalar_type>& input) {
assert(input.rows() == input.columns());
size_t n = input.rows();
matrix<scalar_type> result(n, n);
for (size_t i = 0; i < n; ++i) {
for (size_t k = 0; k < i; ++k) {
scalar_type value = input(i, k);
for (size_t j = 0; j < k; ++j)
value -= result(i, j) * result(k, j);
result(i, k) = value/result(k, k);
}
scalar_type value = input(i, i);
for (size_t j = 0; j < i; ++j)
value -= result(i, j) * result(i, j);
result(i, i) = std::sqrt(value);
}
return result;
}
void print_cholesky_factor(const matrix<double>& matrix) {
std::cout << "Matrix:\n";
print(std::cout, matrix);
std::cout << "Cholesky factor:\n";
print(std::cout, cholesky_factor(matrix));
}
int main() {
matrix<double> matrix1(3, 3,
{{25, 15, -5},
{15, 18, 0},
{-5, 0, 11}});
print_cholesky_factor(matrix1);
matrix<double> matrix2(4, 4,
{{18, 22, 54, 42},
{22, 70, 86, 62},
{54, 86, 174, 134},
{42, 62, 134, 106}});
print_cholesky_factor(matrix2);
return 0;
}
| fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
|
Write the same code in Rust as shown below in Go. | package main
import (
"fmt"
"math"
)
type symmetric struct {
order int
ele []float64
}
type lower struct {
order int
ele []float64
}
func (s *symmetric) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range s.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j, col := diag+row, row; col < s.order; j += col {
fmt.Printf(eleFmt, s.ele[j])
col++
}
fmt.Println()
row++
diag += row
}
}
}
func (l *lower) print() {
const eleFmt = "%10.5f "
row, diag := 1, 0
for i, e := range l.ele {
fmt.Printf(eleFmt, e)
if i == diag {
for j := row; j < l.order; j++ {
fmt.Printf(eleFmt, 0.)
}
fmt.Println()
row++
diag += row
}
}
}
func (a *symmetric) choleskyLower() *lower {
l := &lower{a.order, make([]float64, len(a.ele))}
row, col := 1, 1
dr := 0
dc := 0
for i, e := range a.ele {
if i < dr {
d := (e - l.ele[i]) / l.ele[dc]
l.ele[i] = d
ci, cx := col, dc
for j := i + 1; j <= dr; j++ {
cx += ci
ci++
l.ele[j] += d * l.ele[cx]
}
col++
dc += col
} else {
l.ele[i] = math.Sqrt(e - l.ele[i])
row++
dr += row
col = 1
dc = 0
}
}
return l
}
func main() {
demo(&symmetric{3, []float64{
25,
15, 18,
-5, 0, 11}})
demo(&symmetric{4, []float64{
18,
22, 70,
54, 86, 174,
42, 62, 134, 106}})
}
func demo(a *symmetric) {
fmt.Println("A:")
a.print()
fmt.Println("L:")
a.choleskyLower().print()
}
| fn cholesky(mat: Vec<f64>, n: usize) -> Vec<f64> {
let mut res = vec![0.0; mat.len()];
for i in 0..n {
for j in 0..(i+1){
let mut s = 0.0;
for k in 0..j {
s += res[i * n + k] * res[j * n + k];
}
res[i * n + j] = if i == j { (mat[i * n + i] - s).sqrt() } else { (1.0 / res[j * n + j] * (mat[i * n + j] - s)) };
}
}
res
}
fn show_matrix(matrix: Vec<f64>, n: usize){
for i in 0..n {
for j in 0..n {
print!("{:.4}\t", matrix[i * n + j]);
}
println!("");
}
println!("");
}
fn main(){
let dimension = 3 as usize;
let m1 = vec![25.0, 15.0, -5.0,
15.0, 18.0, 0.0,
-5.0, 0.0, 11.0];
let res1 = cholesky(m1, dimension);
show_matrix(res1, dimension);
let dimension = 4 as usize;
let m2 = vec![18.0, 22.0, 54.0, 42.0,
22.0, 70.0, 86.0, 62.0,
54.0, 86.0, 174.0, 134.0,
42.0, 62.0, 134.0, 106.0];
let res2 = cholesky(m2, dimension);
show_matrix(res2, dimension);
}
|
Produce a language-to-language conversion: from Ada to C#, same semantics. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Ensure the translated C code behaves exactly like the original Ada snippet. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the Ada version. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Transform the following Ada implementation into Go, maintaining the same output and logic. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Convert this Ada snippet to Java and keep its semantics consistent. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Write the same algorithm in Python as shown in this Ada implementation. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Rewrite this program in VB while keeping its functionality equivalent to the Ada version. | with Prime_Numbers, Ada.Text_IO;
procedure Test_Kth_Prime is
package Integer_Numbers is new
Prime_Numbers (Natural, 0, 1, 2);
use Integer_Numbers;
Out_Length: constant Positive := 10;
N: Positive;
begin
for K in 1 .. 5 loop
Ada.Text_IO.Put("K =" & Integer'Image(K) &": ");
N := 2;
for I in 1 .. Out_Length loop
while Decompose(N)'Length /= K loop
N := N + 1;
end loop;
Ada.Text_IO.Put(Integer'Image(Integer(N)));
N := N + 1;
end loop;
Ada.Text_IO.New_Line;
end loop;
end Test_Kth_Prime;
| Private Function kprime(ByVal n As Integer, k As Integer) As Boolean
Dim p As Integer, factors As Integer
p = 2
factors = 0
Do While factors < k And p * p <= n
Do While n Mod p = 0
n = n / p
factors = factors + 1
Loop
p = p + 1
Loop
factors = factors - (n > 1)
kprime = factors = k
End Function
Private Sub almost_primeC()
Dim nextkprime As Integer, count As Integer
Dim k As Integer
For k = 1 To 5
Debug.Print "k ="; k; ":";
nextkprime = 2
count = 0
Do While count < 10
If kprime(nextkprime, k) Then
Debug.Print " "; Format(CStr(nextkprime), "@@@@@");
count = count + 1
End If
nextkprime = nextkprime + 1
Loop
Debug.Print
Next k
End Sub
|
Maintain the same structure and functionality when rewriting this code in C. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Produce a language-to-language conversion: from Arturo to C#, same semantics. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Change the following Arturo code into C++ without altering its purpose. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Change the following Arturo code into Java without altering its purpose. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Keep all operations the same but rewrite the snippet in VB. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Port the provided Arturo code into Go while preserving the original functionality. | almostPrime: function [k, listLen][
result: new []
test: 2
c: 0
while [c < listLen][
i: 2
m: 0
n: test
while [i =< n][
if? zero? n % i [
n: n / i
m: m + 1
]
else -> i: i + 1
]
if m = k [
'result ++ test
c: c + 1
]
test: test + 1
]
return result
]
loop 1..5 'x ->
print ["k:" x "=>" almostPrime x 10]
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Transform the following AutoHotKey implementation into C, maintaining the same output and logic. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Generate a C# translation of this AutoHotKey snippet without changing its computational steps. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Write a version of this AutoHotKey function in Java with identical behavior. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Change the programming language of this snippet from AutoHotKey to Python without modifying what it does. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Write the same code in VB as shown below in AutoHotKey. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Produce a language-to-language conversion: from AutoHotKey to Go, same semantics. | kprime(n,k) {
p:=2, f:=0
while( (f<k) && (p*p<=n) ) {
while ( 0==mod(n,p) ) {
n/=p
f++
}
p++
}
return f + (n>1) == k
}
k:=1, results:=""
while( k<=5 ) {
i:=2, c:=0, results:=results "k =" k ":"
while( c<10 ) {
if (kprime(i,k)) {
results:=results " " i
c++
}
i++
}
results:=results "`n"
k++
}
MsgBox % results
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Port the following code from AWK to C with equivalent syntax and logic. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Write the same algorithm in C# as shown in this AWK implementation. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Port the provided AWK code into C++ while preserving the original functionality. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Translate this program into Java but keep the logic exactly as in AWK. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Preserve the algorithm and functionality while converting the code from AWK to Python. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Rewrite this program in VB while keeping its functionality equivalent to the AWK version. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Rewrite this program in Go while keeping its functionality equivalent to the AWK version. |
BEGIN {
for (k=1; k<=5; k++) {
printf("%d:",k)
c = 0
i = 1
while (c < 10) {
if (kprime(++i,k)) {
printf(" %d",i)
c++
}
}
printf("\n")
}
exit(0)
}
function kprime(n,k, f,p) {
for (p=2; f<k && p*p<=n; p++) {
while (n % p == 0) {
n /= p
f++
}
}
return(f + (n > 1) == k)
}
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Produce a language-to-language conversion: from Clojure to C, same semantics. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Port the provided Clojure code into C# while preserving the original functionality. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Generate a C++ translation of this Clojure snippet without changing its computational steps. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in Java so it works the same as the original Clojure code. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Transform the following Clojure implementation into Python, maintaining the same output and logic. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Keep all operations the same but rewrite the snippet in VB. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Change the following Clojure code into Go without altering its purpose. | (ns clojure.examples.almostprime
(:gen-class))
(defn divisors [n]
" Finds divisors by looping through integers 2, 3,...i.. up to sqrt (n) [note: rather than compute sqrt(), test with i*i <=n] "
(let [div (some #(if (= 0 (mod n %)) % nil) (take-while #(<= (* % %) n) (iterate inc 2)))]
(if div
(into [] (concat (divisors div) (divisors (/ n div))))
[n])))
(defn divisors-k [k n]
" Finds n numbers with k divisors. Does this by looping through integers 2, 3, ... filtering (passing) ones with k divisors and
taking the first n "
(->> (iterate inc 2)
(map divisors)
(filter #(= (count %) k))
(take n)
(map #(apply * %))))
(println (for [k (range 1 6)]
(println "k:" k (divisors-k k 10))))
}
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Produce a language-to-language conversion: from Common_Lisp to C, same semantics. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Convert the following code from Common_Lisp to C#, ensuring the logic remains intact. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Generate a Java translation of this Common_Lisp snippet without changing its computational steps. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Transform the following Common_Lisp implementation into Python, maintaining the same output and logic. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Change the following Common_Lisp code into VB without altering its purpose. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Translate the given Common_Lisp code snippet into Go without altering its behavior. | (defun start ()
(loop for k from 1 to 5
do (format t "k = ~a: ~a~%" k (collect-k-almost-prime k))))
(defun collect-k-almost-prime (k &optional (d 2) (lst nil))
(cond ((= (length lst) 10) (reverse lst))
((= (?-primality d) k) (collect-k-almost-prime k (+ d 1) (cons d lst)))
(t (collect-k-almost-prime k (+ d 1) lst))))
(defun ?-primality (n &optional (d 2) (c 0))
(cond ((> d (isqrt n)) (+ c 1))
((zerop (rem n d)) (?-primality (/ n d) d (+ c 1)))
(t (?-primality n (+ d 1) c))))
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Please provide an equivalent version of this D code in C. | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Transform the following D implementation into C#, maintaining the same output and logic. | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Keep all operations the same but rewrite the snippet in C++. | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Can you help me rewrite this code in Python instead of D, keeping it the same logically? | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Port the provided D code into VB while preserving the original functionality. | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Convert the following code from D to Go, ensuring the logic remains intact. | import std.stdio, std.algorithm, std.traits;
Unqual!T[] decompose(T)(in T number) pure nothrow
in {
assert(number > 1);
} body {
typeof(return) result;
Unqual!T n = number;
for (Unqual!T i = 2; n % i == 0; n /= i)
result ~= i;
for (Unqual!T i = 3; n >= i * i; i += 2)
for (; n % i == 0; n /= i)
result ~= i;
if (n != 1)
result ~= n;
return result;
}
void main() {
enum outLength = 10;
foreach (immutable k; 1 .. 6) {
writef("K = %d: ", k);
auto n = 2;
foreach (immutable i; 1 .. outLength + 1) {
while (n.decompose.length != k)
n++;
write(n, " ");
n++;
}
writeln;
}
}
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Write the same algorithm in C as shown in this Delphi implementation. | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Change the following Delphi code into C# without altering its purpose. | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Change the programming language of this snippet from Delphi to C++ without modifying what it does. | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in Java so it works the same as the original Delphi code. | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| public class AlmostPrime {
public static void main(String[] args) {
for (int k = 1; k <= 5; k++) {
System.out.print("k = " + k + ":");
for (int i = 2, c = 0; c < 10; i++) {
if (kprime(i, k)) {
System.out.print(" " + i);
c++;
}
}
System.out.println("");
}
}
public static boolean kprime(int n, int k) {
int f = 0;
for (int p = 2; f < k && p * p <= n; p++) {
while (n % p == 0) {
n /= p;
f++;
}
}
return f + ((n > 1) ? 1 : 0) == k;
}
}
|
Can you help me rewrite this code in Python instead of Delphi, keeping it the same logically? | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| from prime_decomposition import decompose
from itertools import islice, count
try:
from functools import reduce
except:
pass
def almostprime(n, k=2):
d = decompose(n)
try:
terms = [next(d) for i in range(k)]
return reduce(int.__mul__, terms, 1) == n
except:
return False
if __name__ == '__main__':
for k in range(1,6):
print('%i: %r' % (k, list(islice((n for n in count() if almostprime(n, k)), 10))))
|
Port the following code from Delphi to VB with equivalent syntax and logic. | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| for k = 1 to 5
print "k = "; k; " :";
i = 2
c = 0
while c < 10
if kPrime(i, k) then
print " "; using("###", i);
c = c +1
end if
i = i +1
wend
print
next k
end
function kPrime(n, k)
f = 0
for i = 2 to n
while n mod i = 0
if f = k then kPrime = 0
f = f +1
n = int(n / i)
wend
next i
kPrime = abs(f = k)
end function
|
Write the same code in Go as shown below in Delphi. | program AlmostPrime;
function IsKPrime(const n, k: Integer): Boolean;
var
p, f, v: Integer;
begin
f := 0;
p := 2;
v := n;
while (f < k) and (p*p <= n) do begin
while (v mod p) = 0 do begin
v := v div p;
Inc(f);
end;
Inc(p);
end;
if v > 1 then Inc(f);
Result := f = k;
end;
var
i, c, k: Integer;
begin
for k := 1 to 5 do begin
Write('k = ', k, ':');
c := 0;
i := 2;
while c < 10 do begin
if IsKPrime(i, k) then begin
Write(' ', i);
Inc(c);
end;
Inc(i);
end;
WriteLn;
end;
end.
| package main
import "fmt"
func kPrime(n, k int) bool {
nf := 0
for i := 2; i <= n; i++ {
for n%i == 0 {
if nf == k {
return false
}
nf++
n /= i
}
}
return nf == k
}
func gen(k, n int) []int {
r := make([]int, n)
n = 2
for i := range r {
for !kPrime(n, k) {
n++
}
r[i] = n
n++
}
return r
}
func main() {
for k := 1; k <= 5; k++ {
fmt.Println(k, gen(k, 10))
}
}
|
Rewrite the snippet below in C so it works the same as the original Elixir code. | defmodule Factors do
def factors(n), do: factors(n,2,[])
defp factors(1,_,acc), do: acc
defp factors(n,k,acc) when rem(n,k)==0, do: factors(div(n,k),k,[k|acc])
defp factors(n,k,acc) , do: factors(n,k+1,acc)
def kfactors(n,k), do: kfactors(n,k,1,1,[])
defp kfactors(_tn,tk,_n,k,_acc) when k == tk+1, do: IO.puts "done! "
defp kfactors(tn,tk,_n,k,acc) when length(acc) == tn do
IO.puts "K:
kfactors(tn,tk,2,k+1,[])
end
defp kfactors(tn,tk,n,k,acc) do
case length(factors(n)) do
^k -> kfactors(tn,tk,n+1,k,acc++[n])
_ -> kfactors(tn,tk,n+1,k,acc)
end
end
end
Factors.kfactors(10,5)
| #include <stdio.h>
int kprime(int n, int k)
{
int p, f = 0;
for (p = 2; f < k && p*p <= n; p++)
while (0 == n % p)
n /= p, f++;
return f + (n > 1) == k;
}
int main(void)
{
int i, c, k;
for (k = 1; k <= 5; k++) {
printf("k = %d:", k);
for (i = 2, c = 0; c < 10; i++)
if (kprime(i, k)) {
printf(" %d", i);
c++;
}
putchar('\n');
}
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the Elixir version. | defmodule Factors do
def factors(n), do: factors(n,2,[])
defp factors(1,_,acc), do: acc
defp factors(n,k,acc) when rem(n,k)==0, do: factors(div(n,k),k,[k|acc])
defp factors(n,k,acc) , do: factors(n,k+1,acc)
def kfactors(n,k), do: kfactors(n,k,1,1,[])
defp kfactors(_tn,tk,_n,k,_acc) when k == tk+1, do: IO.puts "done! "
defp kfactors(tn,tk,_n,k,acc) when length(acc) == tn do
IO.puts "K:
kfactors(tn,tk,2,k+1,[])
end
defp kfactors(tn,tk,n,k,acc) do
case length(factors(n)) do
^k -> kfactors(tn,tk,n+1,k,acc++[n])
_ -> kfactors(tn,tk,n+1,k,acc)
end
end
end
Factors.kfactors(10,5)
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AlmostPrime
{
class Program
{
static void Main(string[] args)
{
foreach (int k in Enumerable.Range(1, 5))
{
KPrime kprime = new KPrime() { K = k };
Console.WriteLine("k = {0}: {1}",
k, string.Join<int>(" ", kprime.GetFirstN(10)));
}
}
}
class KPrime
{
public int K { get; set; }
public bool IsKPrime(int number)
{
int primes = 0;
for (int p = 2; p * p <= number && primes < K; ++p)
{
while (number % p == 0 && primes < K)
{
number /= p;
++primes;
}
}
if (number > 1)
{
++primes;
}
return primes == K;
}
public List<int> GetFirstN(int n)
{
List<int> result = new List<int>();
for (int number = 2; result.Count < n; ++number)
{
if (IsKPrime(number))
{
result.Add(number);
}
}
return result;
}
}
}
|
Preserve the algorithm and functionality while converting the code from Elixir to C++. | defmodule Factors do
def factors(n), do: factors(n,2,[])
defp factors(1,_,acc), do: acc
defp factors(n,k,acc) when rem(n,k)==0, do: factors(div(n,k),k,[k|acc])
defp factors(n,k,acc) , do: factors(n,k+1,acc)
def kfactors(n,k), do: kfactors(n,k,1,1,[])
defp kfactors(_tn,tk,_n,k,_acc) when k == tk+1, do: IO.puts "done! "
defp kfactors(tn,tk,_n,k,acc) when length(acc) == tn do
IO.puts "K:
kfactors(tn,tk,2,k+1,[])
end
defp kfactors(tn,tk,n,k,acc) do
case length(factors(n)) do
^k -> kfactors(tn,tk,n+1,k,acc++[n])
_ -> kfactors(tn,tk,n+1,k,acc)
end
end
end
Factors.kfactors(10,5)
| #include <cstdlib>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <list>
bool k_prime(unsigned n, unsigned k) {
unsigned f = 0;
for (unsigned p = 2; f < k && p * p <= n; p++)
while (0 == n % p) { n /= p; f++; }
return f + (n > 1 ? 1 : 0) == k;
}
std::list<unsigned> primes(unsigned k, unsigned n) {
std::list<unsigned> list;
for (unsigned i = 2;list.size() < n;i++)
if (k_prime(i, k)) list.push_back(i);
return list;
}
int main(const int argc, const char* argv[]) {
using namespace std;
for (unsigned k = 1; k <= 5; k++) {
ostringstream os("");
const list<unsigned> l = primes(k, 10);
for (list<unsigned>::const_iterator i = l.begin(); i != l.end(); i++)
os << setw(4) << *i;
cout << "k = " << k << ':' << os.str() << endl;
}
return EXIT_SUCCESS;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.