Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Rewrite the snippet below in Java so it works the same as the original Julia code. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Produce a functionally identical Python code for the snippet given in Julia. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Generate an equivalent Python version of this Julia code. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Port the provided Julia code into VB while preserving the original functionality. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Convert this Julia snippet to VB and keep its semantics consistent. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Produce a language-to-language conversion: from Julia to Go, same semantics. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Generate an equivalent Go version of this Julia code. | using Memoize, Formatting
@memoize function sternbrocot(n)
if n < 2
return n
elseif iseven(n)
return sternbrocot(div(n, 2))
else
m = div(n - 1, 2)
return sternbrocot(m) + sternbrocot(m + 1)
end
end
function fusclengths(N=100000000)
println("sequence number : fusc value")
maxlen = 0
for i in 0:N
x = sternbrocot(i)
if (len = length(string(x))) > maxlen
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
maxlen = len
end
end
end
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
fusclengths()
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Generate an equivalent C version of this Lua code. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Rewrite the snippet below in C# so it works the same as the original Lua code. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Translate this program into C# but keep the logic exactly as in Lua. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Change the programming language of this snippet from Lua to C++ without modifying what it does. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Lua. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Change the following Lua code into Java without altering its purpose. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Java. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Generate an equivalent Python version of this Lua code. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Translate the given Lua code snippet into Python without altering its behavior. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Rewrite this program in VB while keeping its functionality equivalent to the Lua version. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in VB. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Maintain the same structure and functionality when rewriting this code in Go. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Generate an equivalent Go version of this Lua code. | function fusc(n)
n = math.floor(n)
if n == 0 or n == 1 then
return n
elseif n % 2 == 0 then
return fusc(n / 2)
else
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
end
end
function numLen(n)
local sum = 1
while n > 9 do
n = math.floor(n / 10)
sum = sum + 1
end
return sum
end
function printLargeFuscs(limit)
print("Printing all largest Fusc numbers up to " .. limit)
print("Index
local maxLen = 1
for i=0,limit do
local f = fusc(i)
local le = numLen(f)
if le > maxLen then
maxLen = le
print(string.format("%5d%12d", i, f))
end
end
end
function main()
print("Index
for i=0,60 do
print(string.format("%5d%12d", i, fusc(i)))
end
printLargeFuscs(math.pow(2, 31) - 1)
end
main()
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Translate this program into C but keep the logic exactly as in Mathematica. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Please provide an equivalent version of this Mathematica code in C. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Mathematica to C#. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Translate this program into C# but keep the logic exactly as in Mathematica. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Translate this program into C++ but keep the logic exactly as in Mathematica. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Produce a language-to-language conversion: from Mathematica to C++, same semantics. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Keep all operations the same but rewrite the snippet in Java. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Port the following code from Mathematica to Java with equivalent syntax and logic. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Change the programming language of this snippet from Mathematica to Python without modifying what it does. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Write a version of this Mathematica function in Python with identical behavior. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Maintain the same structure and functionality when rewriting this code in VB. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Write the same code in VB as shown below in Mathematica. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Preserve the algorithm and functionality while converting the code from Mathematica to Go. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Transform the following Mathematica implementation into Go, maintaining the same output and logic. | ClearAll[Fusc]
Fusc[0] := 0
Fusc[1] := 1
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
Fusc /@ Range[0, 60]
res = {{0, 1}};
i = 0;
PrintTemporary[Dynamic[{res, i}]];
While[Length[res] < 6,
f = Fusc[i];
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
AppendTo[res, {i, f}]
];
i++;
];
res
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Please provide an equivalent version of this Nim code in C. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Change the following Nim code into C without altering its purpose. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Convert this Nim block to C#, preserving its control flow and logic. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Can you help me rewrite this code in C++ instead of Nim, keeping it the same logically? | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Write the same algorithm in C++ as shown in this Nim implementation. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Convert this Nim block to Java, preserving its control flow and logic. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Ensure the translated Python code behaves exactly like the original Nim snippet. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Port the provided Nim code into Python while preserving the original functionality. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Produce a language-to-language conversion: from Nim to VB, same semantics. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Please provide an equivalent version of this Nim code in VB. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Change the programming language of this snippet from Nim to Go without modifying what it does. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Produce a functionally identical Go code for the snippet given in Nim. | import strformat
func fusc(n: int): int =
if n == 0 or n == 1:
n
elif n mod 2 == 0:
fusc(n div 2)
else:
fusc((n - 1) div 2) + fusc((n + 1) div 2)
echo "The first 61 Fusc numbers:"
for i in 0..61:
write(stdout, fmt"{fusc(i)} ")
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
echo fmt" n fusc(n)"
echo "--------- ---------"
var maxLength = 0
for i in 0..700_000:
var f = fusc(i)
var length = len($f)
if length > maxLength:
maxLength = length
echo fmt"{i:9} {f:9}"
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Please provide an equivalent version of this OCaml code in C. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Generate a C translation of this OCaml snippet without changing its computational steps. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Transform the following OCaml implementation into C#, maintaining the same output and logic. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Change the following OCaml code into C# without altering its purpose. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Produce a functionally identical C++ code for the snippet given in OCaml. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Rewrite this program in C++ while keeping its functionality equivalent to the OCaml version. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Translate the given OCaml code snippet into Java without altering its behavior. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Write the same code in Java as shown below in OCaml. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Change the programming language of this snippet from OCaml to Python without modifying what it does. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Rewrite the snippet below in Python so it works the same as the original OCaml code. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Generate a VB translation of this OCaml snippet without changing its computational steps. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Change the programming language of this snippet from OCaml to VB without modifying what it does. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Can you help me rewrite this code in Go instead of OCaml, keeping it the same logically? | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Please provide an equivalent version of this OCaml code in Go. | let seq_fusc =
let rec next x xs () =
match xs () with
| Seq.Nil -> assert false
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
in
let rec tail () = Seq.Cons (1, next 1 tail) in
Seq.cons 0 (Seq.cons 1 tail)
let seq_first_of_lengths =
let rec next i l sq () =
match sq () with
| Seq.Nil -> Seq.Nil
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
| Cons (_, xs) -> next (succ i) l xs ()
in next 0 10
let () =
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
and () =
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Rewrite the snippet below in C so it works the same as the original Pascal code. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Transform the following Pascal implementation into C, maintaining the same output and logic. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Transform the following Pascal implementation into C#, maintaining the same output and logic. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Change the programming language of this snippet from Pascal to C# without modifying what it does. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Change the following Pascal code into C++ without altering its purpose. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Convert this Pascal snippet to C++ and keep its semantics consistent. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Produce a language-to-language conversion: from Pascal to Java, same semantics. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Convert the following code from Pascal to Java, ensuring the logic remains intact. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Write a version of this Pascal function in Python with identical behavior. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Port the provided Pascal code into Python while preserving the original functionality. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Port the following code from Pascal to VB with equivalent syntax and logic. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Transform the following Pascal implementation into VB, maintaining the same output and logic. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Generate an equivalent Go version of this Pascal code. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Write the same algorithm in Go as shown in this Pascal implementation. | program fusc;
uses
sysutils;
const
MaxIdx = 1253 * 1000 * 1000;
MaxIdx = 19573420;
type
tFuscElem = LongWord;
tFusc = array of tFuscElem;
var
FuscField : tFusc;
function commatize(n:NativeUint):string;
var
l,i : NativeUint;
begin
str(n,result);
l := length(result);
if l < 4 then
exit;
i := l+ (l-1) DIV 3;
setlength(result,i);
While i <> l do
Begin
result[i]:= result[l];result[i-1]:= result[l-1];
result[i-2]:= result[l-2];result[i-3]:= ',';
dec(i,4);dec(l,3);
end;
end;
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
Begin
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
IF EndIdx > High(FF) then EndIdx := High(FF);
For StartIdx := StartIdx to EndIdx do
write(FF[StartIdx],' ');
writeln;
end;
procedure FuscCalc(var FF:tFusc);
var
pFFn,pFFi : ^tFuscElem;
i,n,sum : NativeUint;
Begin
FF[0]:= 0;
FF[1]:= 1;
n := 2;
i := 1;
pFFn := @FF[n];
pFFi := @FF[i];
sum := pFFi^;
while n <= MaxIdx-2 do
begin
pFFn^ := sum;
inc(pFFi);
inc(pFFn);
sum := sum+pFFi^;
pFFn^:= sum;
sum := pFFi^;
inc(pFFn);
inc(n,2);
end;
end;
procedure OutHeader(base:NativeInt);
begin
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
writeln('======':10,' =======':14);
end;
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
var
pFF : ^tFuscElem;
Dig,
i,lastIdx: NativeInt;
Begin
OutHeader(base);
Dig := -1;
i := 0;
lastIdx := 0;
pFF := @FF[0];
repeat
repeat
inc(pFF);
inc(i);
until pFF^ >Dig;
if i>= MaxIdx then
BREAK;
write(commatize(pFF^):10,commatize(i):14);
IF lastIdx> 0 then
write(i/lastIdx:12:7);
writeln;
lastIdx := i;
IF Dig >0 then
Dig := Dig*Base+Base-1
else
Dig := Base-1;
until false;
writeln;
end;
BEGIN
setlength(FuscField,MaxIdx);
FuscCalc(FuscField);
writeln('First 61 fusc numbers:');
OutFusc(0,60,FuscField);
CheckFuscDigits(FuscField,10);
CheckFuscDigits(FuscField,11);
setlength(FuscField,0);
readln;
END.
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Ensure the translated C code behaves exactly like the original Perl snippet. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Write the same algorithm in C# as shown in this Perl implementation. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Preserve the algorithm and functionality while converting the code from Perl to C#. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Translate the given Perl code snippet into C++ without altering its behavior. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Translate this program into C++ but keep the logic exactly as in Perl. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Write the same code in Java as shown below in Perl. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Please provide an equivalent version of this Perl code in Java. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Please provide an equivalent version of this Perl code in Python. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Write the same code in Python as shown below in Perl. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Write the same code in VB as shown below in Perl. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Can you help me rewrite this code in VB instead of Perl, keeping it the same logically? | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| Module Module1
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
Function fusc(n As Integer) As Integer
If n < l.Count Then Return l(n)
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
l.Add(fusc)
End Function
Sub Main(args As String())
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
For i As Integer = 0 To Integer.MaxValue
Dim f As Integer = fusc(i)
If lst Then
If i < 61 Then
Console.Write("{0} ", f)
Else
lst = False
Console.WriteLine()
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
End If
End If
Dim t As Integer = f.ToString.Length
If t > w Then
w = t
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
If Not lst Then Console.WriteLine(res) : res = ""
c += 1 : If c > 5 Then Exit For
End If
Next : l.Clear()
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Change the programming language of this snippet from Perl to Go without modifying what it does. | use strict;
use warnings;
use feature 'say';
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub stern_diatomic {
my ($p,$q,$i) = (0,1,shift);
while ($i) {
if ($i & 1) { $p += $q; } else { $q += $p; }
$i >>= 1;
}
$p;
}
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
say "\nIndex and value for first term longer than any previous:";
my $i = 0;
my $l = -1;
while ($l < 5) {
my $v = stern_diatomic($i);
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
$i++;
}
| package main
import (
"fmt"
"strconv"
)
func fusc(n int) []int {
if n <= 0 {
return []int{}
}
if n == 1 {
return []int{0}
}
res := make([]int, n)
res[0] = 0
res[1] = 1
for i := 2; i < n; i++ {
if i%2 == 0 {
res[i] = res[i/2]
} else {
res[i] = res[(i-1)/2] + res[(i+1)/2]
}
}
return res
}
func fuscMaxLen(n int) [][2]int {
maxLen := -1
maxFusc := -1
f := fusc(n)
var res [][2]int
for i := 0; i < n; i++ {
if f[i] <= maxFusc {
continue
}
maxFusc = f[i]
le := len(strconv.Itoa(f[i]))
if le > maxLen {
res = append(res, [2]int{i, f[i]})
maxLen = le
}
}
return res
}
func commatize(n int) string {
s := fmt.Sprintf("%d", n)
if n < 0 {
s = s[1:]
}
le := len(s)
for i := le - 3; i >= 1; i -= 3 {
s = s[0:i] + "," + s[i:]
}
if n >= 0 {
return s
}
return "-" + s
}
func main() {
fmt.Println("The first 61 fusc numbers are:")
fmt.Println(fusc(61))
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
res := fuscMaxLen(20000000)
for i := 0; i < len(res); i++ {
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
}
}
|
Generate an equivalent C version of this Racket code. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Write the same code in C as shown below in Racket. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| #include<limits.h>
#include<stdio.h>
int fusc(int n){
if(n==0||n==1)
return n;
else if(n%2==0)
return fusc(n/2);
else
return fusc((n-1)/2) + fusc((n+1)/2);
}
int numLen(int n){
int sum = 1;
while(n>9){
n = n/10;
sum++;
}
return sum;
}
void printLargeFuscs(int limit){
int i,f,len,maxLen = 1;
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
for(i=0;i<=limit;i++){
f = fusc(i);
len = numLen(f);
if(len>maxLen){
maxLen = len;
printf("\n%5d%12d",i,f);
}
}
}
int main()
{
int i;
printf("Index-------Value");
for(i=0;i<61;i++)
printf("\n%5d%12d",i,fusc(i));
printLargeFuscs(INT_MAX);
return 0;
}
|
Produce a functionally identical C# code for the snippet given in Racket. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Port the following code from Racket to C# with equivalent syntax and logic. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| using System;
using System.Collections.Generic;
static class program
{
static int n = 61;
static List<int> l = new List<int>() { 0, 1 };
static int fusc(int n)
{
if (n < l.Count) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.Add(f); return f;
}
static void Main(string[] args)
{
bool lst = true; int w = -1, c = 0, t;
string fs = "{0,11:n0} {1,-9:n0}", res = "";
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
for (int i = 0; i < int.MaxValue; i++)
{
int f = fusc(i); if (lst)
{
if (i < 61) Console.Write("{0} ", f);
else
{
lst = false;
Console.WriteLine();
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
}
}
if ((t = f.ToString().Length) > w)
{
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
}
}
l.Clear();
}
}
|
Transform the following Racket implementation into C++, maintaining the same output and logic. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Racket. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| #include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
const int n = 61;
std::vector<int> l{ 0, 1 };
int fusc(int n) {
if (n < l.size()) return l[n];
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
l.push_back(f);
return f;
}
int main() {
bool lst = true;
int w = -1;
int c = 0;
int t;
std::string res;
std::cout << "First " << n << " numbers in the fusc sequence:\n";
for (int i = 0; i < INT32_MAX; i++) {
int f = fusc(i);
if (lst) {
if (i < 61) {
std::cout << f << ' ';
} else {
lst = false;
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
std::cout << res << '\n';
res = "";
}
}
std::stringstream ss;
ss << f;
t = ss.str().length();
ss.str("");
ss.clear();
if (t > w) {
w = t;
res += (res == "" ? "" : "\n");
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
res += ss.str();
if (!lst) {
std::cout << res << '\n';
res = "";
}
if (++c > 5) {
break;
}
}
}
return 0;
}
|
Write a version of this Racket function in Java with identical behavior. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Convert this Racket snippet to Java and keep its semantics consistent. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| public class FuscSequence {
public static void main(String[] args) {
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
for ( int n = 0 ; n < 61 ; n++ ) {
System.out.printf("%,d ", fusc[n]);
}
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
int start = 0;
for (int i = 0 ; i <= 5 ; i++ ) {
int val = i != 0 ? (int) Math.pow(10, i) : -1;
for ( int j = start ; j < FUSC_MAX ; j++ ) {
if ( fusc[j] > val ) {
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
start = j;
break;
}
}
}
}
private static final int FUSC_MAX = 30000000;
private static int[] fusc = new int[FUSC_MAX];
static {
fusc[0] = 0;
fusc[1] = 1;
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
}
}
}
|
Rewrite the snippet below in Python so it works the same as the original Racket code. | #lang racket
(require racket/generator)
(define (memoize f)
(define table (make-hash))
(λ args (hash-ref! table args (thunk (apply f args)))))
(define fusc
(memoize
(λ (n)
(cond
[(<= n 1) n]
[(even? n) (fusc (/ n 2))]
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
(define (comma x)
(string-join
(reverse
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
(cond
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
[else (string digit)])))
""))
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
(newline)
(define gen
(in-generator
(let loop ([prev 0] [i 0])
(define result (fusc i))
(define len (string-length (~a result)))
(cond
[(> len prev)
(yield (list i result))
(loop len (add1 i))]
[else (loop prev (add1 i))]))))
(for ([i (in-range 5)] [x gen])
(match-define (list index result) x)
(printf "~a: ~a\n" (comma index) (comma result)))
| from collections import deque
from itertools import islice, count
def fusc():
q = deque([1])
yield 0
yield 1
while True:
x = q.popleft()
q.append(x)
yield x
x += q[0]
q.append(x)
yield x
def longest_fusc():
sofar = 0
for i, f in zip(count(), fusc()):
if f >= sofar:
yield(i, f)
sofar = 10 * sofar or 10
print('First 61:')
print(list(islice(fusc(), 61)))
print('\nLength records:')
for i, f in islice(longest_fusc(), 6):
print(f'fusc({i}) = {f}')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.