Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <string> #include <chrono> #include <cmath> #include <locale> using namespace std; using namespace chrono; unsigned int js(int l, int n) { unsigned int res = 0, f = 1; double lf = log(2) / log(10), ip; for (int i = l; i > 10; i /= 10) f *= 10; while (n > 0) if ((int)(f * pow(10, modf(++res * ...
function p(L, n) @assert(L > 0 && n > 0) places, logof2, nfound = trunc(log(10, L)), log(10, 2), 0 for i in 1:typemax(Int) if L == trunc(10^(((i * logof2) % 1) + places)) && (nfound += 1) == n return i end end end for (L, n) in [(12, 1), (12, 2), (123, 45), (123, 12345), (12...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
using Combinatorics const s2cache = Dict() function stirlings2(n, k) if haskey(s2cache, Pair(n, k)) return s2cache[Pair(n, k)] elseif n < 0 throw(DomainError(n, "n must be nonnegative")) elseif n == k == 0 return one(n) elseif n == 0 || k == 0 return zero(n) elseif ...
Please provide an equivalent version of this C++ code in Julia.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class stirling2 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer stirling2::get(int n, int k) { if (k == n) return 1; ...
using Combinatorics const s2cache = Dict() function stirlings2(n, k) if haskey(s2cache, Pair(n, k)) return s2cache[Pair(n, k)] elseif n < 0 throw(DomainError(n, "n must be nonnegative")) elseif n == k == 0 return one(n) elseif n == 0 || k == 0 return zero(n) elseif ...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <cassert> #include <algorithm> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; bool is_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25); } template <typename integer> class n_smooth_generator { public: explicit n_smooth_gen...
using Primes function pierponts(N, firstkind = true) ret, incdec = BigInt[], firstkind ? 1 : -1 for k2 in 0:10000, k3 in 0:k2, switch in false:true i, j = switch ? (k3, k2) : (k2, k3) n = BigInt(2)^i * BigInt(3)^j + incdec if isprime(n) && !(n in ret) push!(ret, n) ...
Change the following C++ code into Julia without altering its purpose.
#include <algorithm> #include <iostream> #include <vector> std::vector<uint64_t> primes; std::vector<uint64_t> smallPrimes; template <typename T> std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os <...
using Primes function nsmooth(N, needed) nexts, smooths = [BigInt(i) for i in 2:N if isprime(i)], [BigInt(1)] prim, count = deepcopy(nexts), 1 indices = ones(Int, length(nexts)) while count < needed x = minimum(nexts) push!(smooths, x) count += 1 for j in 1:length(nexts)...
Generate an equivalent Julia version of this C++ code.
#include <algorithm> #include <functional> #include <iostream> #include <vector> std::vector<int> primes; struct Seq { public: bool empty() { return p < 0; } int front() { return p; } void popFront() { if (p == 2) { p++; } else { p += 2; ...
using Primes, Combinatorics function primepartition(x::Int64, n::Int64) if n == oftype(n, 1) return isprime(x) ? [x] : Int64[] else for combo in combinations(primes(x), n) if sum(combo) == x return combo end end end return Int64[] end for...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> enum class zd {N00,N01,N10,N11}; class N { private: int dVal = 0, dLen; void _a(int i) { for (;; i++) { if (dLen < i) dLen = i; switch ((zd)((dVal >> (i*2)) & 3)) { case zd::N00: case zd::N01: return; case zd::N10: if (((dVal >> ((i+1)*2)) & 1) != 1) return;...
import Base.*, Base.+, Base.-, Base./, Base.show, Base.!=, Base.==, Base.<=, Base.<, Base.>, Base.>=, Base.divrem const z0 = "0" const z1 = "1" const flipordered = (z1 < z0) mutable struct Z s::String end Z() = Z(z0) Z(z::Z) = Z(z.s) pairlen(x::Z, y::Z) = max(length(x.s), length(y.s)) tolen(x::Z, n::Int) = (s = x.s;...
Keep all operations the same but rewrite the snippet in Julia.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_stirling1 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_stirling1::get(int n, int k) { if (k == 0) ...
using Combinatorics const s1cache = Dict() function stirlings1(n, k, signed::Bool=false) if signed == true && isodd(n - k) return -stirlings1(n, k) elseif haskey(s1cache, Pair(n, k)) return s1cache[Pair(n, k)] elseif n < 0 throw(DomainError(n, "n must be nonnegative")) elseif n...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_stirling1 { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_stirling1::get(int n, int k) { if (k == 0) ...
using Combinatorics const s1cache = Dict() function stirlings1(n, k, signed::Bool=false) if signed == true && isodd(n - k) return -stirlings1(n, k) elseif haskey(s1cache, Pair(n, k)) return s1cache[Pair(n, k)] elseif n < 0 throw(DomainError(n, "n must be nonnegative")) elseif n...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <cmath> #include <utility> #include <vector> #include <stdexcept> using namespace std; typedef std::pair<double, double> Point; double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd) { double dx = lineEnd.first - lineStart.first; double dy = lineEnd....
const Point = Vector{Float64} function perpdist(pt::Point, lnstart::Point, lnend::Point) d = normalize!(lnend .- lnstart) pv = pt .- lnstart pvdot = dot(d, pv) ds = pvdot .* d return norm(pv .- ds) end function rdp(plist::Vector{Point}, ϵ::Float64 = 1.0) if length(plist) < 2 ...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <cmath> #include <utility> #include <vector> #include <stdexcept> using namespace std; typedef std::pair<double, double> Point; double PerpendicularDistance(const Point &pt, const Point &lineStart, const Point &lineEnd) { double dx = lineEnd.first - lineStart.first; double dy = lineEnd....
const Point = Vector{Float64} function perpdist(pt::Point, lnstart::Point, lnend::Point) d = normalize!(lnend .- lnstart) pv = pt .- lnstart pvdot = dot(d, pv) ds = pvdot .* d return norm(pv .- ds) end function rdp(plist::Vector{Point}, ϵ::Float64 = 1.0) if length(plist) < 2 ...
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> #include <cmath> #include <cassert> using namespace std; #define PI 3.14159265359 class Vector { public: Vector(double ix, double iy, char mode) { if(mode=='a') { x=ix*cos(iy); y=ix*sin(iy); } else { x=ix; ...
module SpatialVectors export SpatialVector struct SpatialVector{N, T} coord::NTuple{N, T} end SpatialVector(s::NTuple{N,T}, e::NTuple{N,T}) where {N,T} = SpatialVector{N, T}(e .- s) function SpatialVector(∠::T, val::T) where T θ = atan(∠) x = val * cos(θ) y = val * sin(θ) return SpatialVector...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { ...
struct Point{T<:AbstractFloat} x::T y::T end Point{T}() where T<:AbstractFloat = Point{T}(Inf, Inf) Point() = Point{Float64}() Base.show(io::IO, p::Point{T}) where T = iszero(p) ? print(io, "Zero{$T}") : @printf(io, "{%s}(%.3f, %.3f)", T, p.x, p.y) Base.copy(p::Point) = Point(p.x, p.y) Base.iszero(p::Point{T})...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <cmath> #include <iostream> using namespace std; class EllipticPoint { double m_x, m_y; static constexpr double ZeroThreshold = 1e20; static constexpr double B = 7; void Double() noexcept { if(IsZero()) { ...
struct Point{T<:AbstractFloat} x::T y::T end Point{T}() where T<:AbstractFloat = Point{T}(Inf, Inf) Point() = Point{Float64}() Base.show(io::IO, p::Point{T}) where T = iszero(p) ? print(io, "Zero{$T}") : @printf(io, "{%s}(%.3f, %.3f)", T, p.x, p.y) Base.copy(p::Point) = Point(p.x, p.y) Base.iszero(p::Point{T})...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iostream> #include <iomanip> #include <string> #include <cmath> #include <utility> #include <vector> using namespace std; static const double PI = acos(-1.0); double affine_remap(const pair<double, double>& from, double x, const pair<double, double>& to) { return to.first + (x - from.first) * (to.second -...
mutable struct Cheb c::Vector{Float64} min::Float64 max::Float64 end function Cheb(min::Float64, max::Float64, ncoeff::Int, nnodes::Int, fn::Function)::Cheb c = Cheb(Vector{Float64}(ncoeff), min, max) f = Vector{Float64}(nnodes) p = Vector{Float64}(nnodes) z = (max + min) / 2 r = (max -...
Change the following C++ code into Julia without altering its purpose.
#include <iostream> #include <iomanip> #include <string> #include <cmath> #include <utility> #include <vector> using namespace std; static const double PI = acos(-1.0); double affine_remap(const pair<double, double>& from, double x, const pair<double, double>& to) { return to.first + (x - from.first) * (to.second -...
mutable struct Cheb c::Vector{Float64} min::Float64 max::Float64 end function Cheb(min::Float64, max::Float64, ncoeff::Int, nnodes::Int, fn::Function)::Cheb c = Cheb(Vector{Float64}(ncoeff), min, max) f = Vector{Float64}(nnodes) p = Vector{Float64}(nnodes) z = (max + min) / 2 r = (max -...
Produce a language-to-language conversion: from C++ to Julia, same semantics.
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : ...
bwsort(vec) = sort(vec, lt = (a, b) -> string(a) < string(b)) function burrowswheeler_encode(s) if match(r"\x02|\x03", s) != nothing throw("String for Burrows-Wheeler input cannot contain STX or ETX") end s = "\x02" * s * "\x03" String([t[end] for t in bwsort([circshift([c for c in s], n) for n...
Port the provided C++ code into Julia while preserving the original functionality.
#include <algorithm> #include <iostream> #include <vector> const int STX = 0x02; const int ETX = 0x03; void rotate(std::string &a) { char t = a[a.length() - 1]; for (int i = a.length() - 1; i > 0; i--) { a[i] = a[i - 1]; } a[0] = t; } std::string bwt(const std::string &s) { for (char c : ...
bwsort(vec) = sort(vec, lt = (a, b) -> string(a) < string(b)) function burrowswheeler_encode(s) if match(r"\x02|\x03", s) != nothing throw("String for Burrows-Wheeler input cannot contain STX or ETX") end s = "\x02" * s * "\x03" String([t[end] for t in bwsort([circshift([c for c in s], n) for n...
Port the provided C++ code into Julia while preserving the original functionality.
#include <time.h> #include <algorithm> #include <iostream> #include <string> #include <deque> class riffle { public: void shuffle( std::deque<int>* v, int tm ) { std::deque<int> tmp; bool fl; size_t len; std::deque<int>::iterator it; copyTo( v, &tmp ); for( int t = 0; t < tm; t++ ) { std:...
function riffleshuffle!(list::Vector, flips::Integer) len = length(list) llist = similar(list, len÷2 + fld(len, 10)) rlist = similar(list, len÷2 + fld(len, 10)) for _ in Base.OneTo(flips) cut = len ÷ 2 + rand(-1:2:1) * rand(0:fld(len, 10)) copy!(llist, 1,...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <time.h> #include <algorithm> #include <iostream> #include <string> #include <deque> class riffle { public: void shuffle( std::deque<int>* v, int tm ) { std::deque<int> tmp; bool fl; size_t len; std::deque<int>::iterator it; copyTo( v, &tmp ); for( int t = 0; t < tm; t++ ) { std:...
function riffleshuffle!(list::Vector, flips::Integer) len = length(list) llist = similar(list, len÷2 + fld(len, 10)) rlist = similar(list, len÷2 + fld(len, 10)) for _ in Base.OneTo(flips) cut = len ÷ 2 + rand(-1:2:1) * rand(0:fld(len, 10)) copy!(llist, 1,...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <exception> #include <iomanip> #include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac() : num(0), denom(1) {} Frac(int n, int d) { if (d == 0) { throw std::runtime_error("d must not be zero"); } int sign_of_d = d < 0 ? -1 : 1; int g = std::gcd(n,...
function bernoulli(n) A = Vector{Rational{BigInt}}(undef, n + 1) for i in 0:n A[i + 1] = 1 // (i + 1) for j = i:-1:1 A[j] = j * (A[j] - A[j + 1]) end end return n == 1 ? -A[1] : A[1] end function faulhabercoeffs(p) coeffs = Vector{Rational{BigInt}}(undef, p + 1) ...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iostream> #include <numeric> #include <sstream> #include <vector> class Frac { public: Frac(long n, long d) { if (d == 0) { throw new std::runtime_error("d must not be zero"); } long nn = n; long dd = d; if (nn == 0) { dd = 1; } else if (dd < 0) { nn = -nn; dd = -dd; } long g =...
module Faulhaber function bernoulli(n::Integer) n ≥ 0 || throw(DomainError(n, "n must be a positive-or-0 number")) a = fill(0 // 1, n + 1) for m in 1:n a[m] = 1 // (m + 1) for j in m:-1:2 a[j - 1] = (a[j - 1] - a[j]) * j end end return ifelse(n != 1, a[1], -a[1])...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <vector> #include <iostream> #include <cmath> #include <utility> #include <map> #include <iomanip> bool isPrime( int i ) { int stop = std::sqrt( static_cast<double>( i ) ) ; for ( int d = 2 ; d <= stop ; d++ ) if ( i % d == 0 ) return false ; return true ; } class Compare { public : Compa...
using Printf, Primes using DataStructures function counttransitions(upto::Integer) cnt = counter(Pair{Int,Int}) tot = 0 prv, nxt = 2, 3 while nxt ≤ upto push!(cnt, prv % 10 => nxt % 10) prv = nxt nxt = nextprime(nxt + 1) tot += 1 end return sort(Dict(cnt)), tot -...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <vector> std::vector<long> TREE_LIST; std::vector<int> OFFSET; void init() { for (size_t i = 0; i < 32; i++) { if (i == 1) { OFFSET.push_back(1); } else { OFFSET.push_back(0); } } } void append(long t) { TREE_LIST.push_back(1 | ...
bags(n,cache="") = n < 1 ? [(0, "")] : [(c + 1, "(" * s * ")") for (c, s) in bagchain((0, ""), n - 1, n < 2 ? [] : reduce(append!, [bags(x) for x in n-1:-1:1]))] bagchain(x, n, bb, start=1) = n < 1 ? [x] : reduce(append!, [bagchain((x[1] + bb[i][1], x[2] * bb[i][2]), n - bb[i][1], bb, i) fo...
Please provide an equivalent version of this C++ code in Julia.
#include <bitset> #include <stdio.h> #define SIZE 80 #define RULE 30 #define RULE_TEST(x) (RULE & 1 << (7 & (x))) void evolve(std::bitset<SIZE> &s) { int i; std::bitset<SIZE> t(0); t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] ); t[ 0] = RULE_TEST( s[...
function evolve(state, rule, N=64) B(x) = UInt64(1) << x for p in 0:9 b = UInt64(0) for q in 7:-1:0 st = UInt64(state) b |= (st & 1) << q state = UInt64(0) for i in 0:N-1 t1 = (i > 0) ? st >> (i - 1) : st >> (N - 1) ...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <algorithm> #include <iostream> #include <iterator> #include <vector> const int luckySize = 60000; std::vector<int> luckyEven(luckySize); std::vector<int> luckyOdd(luckySize); void init() { for (int i = 0; i < luckySize; ++i) { luckyEven[i] = i * 2 + 2; luckyOdd[i] = i * 2 + 1; } } v...
using Base, StringDistances struct Lucky start::Int nmax::Int Lucky(iseven, nmax) = new(iseven ? 2 : 1, nmax) end struct LuckyState nextindex::Int sequence::Vector{Int} end Base.eltype(iter::Lucky) = Int function Base.iterate(iter::Lucky, state = LuckyState(1, collect(iter.start:2:iter.nmax))) ...
Transform the following C++ implementation into Julia, maintaining the same output and logic.
#include <algorithm> #include <complex> #include <iomanip> #include <iostream> std::complex<double> inv(const std::complex<double>& c) { double denom = c.real() * c.real() + c.imag() * c.imag(); return std::complex<double>(c.real() / denom, -c.imag() / denom); } class QuaterImaginary { public: QuaterImagi...
import Base.show, Base.parse, Base.+, Base.-, Base.*, Base./, Base.^ function inbase4(charvec::Vector) if (!all(x -> x in ['-', '0', '1', '2', '3', '.'], charvec)) || ((x = findlast(x -> x == '-', charvec)) != nothing && x > findfirst(x -> x != '-', charvec)) || ((x = findall(x -> x == '.', charvec...
Port the provided C++ code into Julia while preserving the original functionality.
#include <random> #include <map> #include <string> #include <iostream> #include <cmath> #include <iomanip> int main( ) { std::random_device myseed ; std::mt19937 engine ( myseed( ) ) ; std::normal_distribution<> normDistri ( 2 , 3 ) ; std::map<int , int> normalFreq ; int sum = 0 ; double mean = 0.0 ...
using Printf, Distributions, Gadfly data = rand(Normal(0, 1), 1000) @printf("N = %i\n", length(data)) @printf("μ = %2.2f\tσ = %2.2f\n", mean(data), std(data)) @printf("range = (%2.2f, %2.2f\n)", minimum(data), maximum(data)) h = plot(x=data, Geom.histogram) draw(PNG("norm_hist.png", 10cm, 10cm), h)
Write a version of this C++ function in Julia with identical behavior.
#include <iostream> #include <numeric> #include <vector> template <typename T> std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) { auto it = v.cbegin(); auto end = v.cend(); os << '['; if (it != end) { os << *it; it = std::next(it); } while (it != end) { ...
immutable TProblem{T<:Integer,U<:String} sd::Array{Array{T,1},1} toc::Array{T,2} labels::Array{Array{U,1},1} tsort::Array{Array{T,2}, 1} end function TProblem{T<:Integer,U<:String}(s::Array{T,1}, d::Array{T,1}, toc::Array{T...
Maintain the same structure and functionality when rewriting this code in Julia.
#include <iostream> #include <vector> __int128 imax(__int128 a, __int128 b) { if (a > b) { return a; } return b; } __int128 ipow(__int128 b, __int128 n) { if (n == 0) { return 1; } if (n == 1) { return b; } __int128 res = b; while (n > 1) { res *= b...
function B10(n) for i in Int128(1):typemax(Int128) q, b10, place = i, zero(Int128), one(Int128) while q > 0 q, r = divrem(q, 2) if r != 0 b10 += place end place *= 10 end if b10 % n == 0 return b10 en...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <iostream> #include <sstream> #include <iomanip> using namespace std; class magicSqr { public: magicSqr() { sqr = 0; } ~magicSqr() { if( sqr ) delete [] sqr; } void create( int d ) { if( sqr ) delete [] sqr; if( d & 1 ) d++; while( d % 4 == 0 ) { d += 2; } sz = ...
function oddmagicsquare(order) if iseven(order) order += 1 end q = zeros(Int, (order, order)) p = 1 i = div(order, 2) + 1 j = 1 while p <= order * order q[i, j] = p ti = (i + 1 > order) ? 1 : i + 1 tj = (j - 1 < 1) ? order : j - 1 if q[ti, tj] != 0 ...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <algorithm> #include <iostream> #include <numeric> #include <vector> std::vector<int> divisors(int n) { std::vector<int> divs = { 1 }; std::vector<int> divs2; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { int j = n / i; divs.push_back(i); if (i !...
using Primes function nosuchsum(revsorted, num) if sum(revsorted) < num return true end for (i, n) in enumerate(revsorted) if n > num continue elseif n == num return false elseif !nosuchsum(revsorted[i+1:end], num - n) return false ...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <array> #include <bitset> #include <iostream> using namespace std; struct FieldDetails {string_view Name; int NumBits;}; template <const char *T> consteval auto ParseDiagram() { constexpr string_view rawArt(T); constexpr auto firstBar = rawArt.find("|"); constexpr auto lastBar = rawArt....
diagram = """ +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ID | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ |QR| Opcode |AA|TC|RD|RA| Z | RCODE | +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ | ...
Produce a functionally identical Julia code for the snippet given in C++.
#include <iostream> #include <vector> enum class Piece { empty, black, white }; typedef std::pair<int, int> position; bool isAttacking(const position &queen, const position &pos) { return queen.first == pos.first || queen.second == pos.second || abs(queen.first - pos.first) == abs(que...
using Gtk struct Position row::Int col::Int end function place!(numeach, bsize, bqueens, wqueens) isattack(q, pos) = (q.row == pos.row || q.col == pos.col || abs(q.row - pos.row) == abs(q.col - pos.col)) noattack(qs, pos) = !any(x -> isattack(x, pos), qs) positionopen(bqs, ...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> std::vector<int> smallPrimes; bool is_prime(size_t test) { if (test < 2) { return false; } if (test % 2 == 0) { return test == 2; } for (size_t d = 3; d * d <= test; d += 2) { if (test % d == 0) { return false; } ...
using Primes function countdivisors(n) f = [one(n)] for (p, e) in factor(n) f = reduce(vcat, [f * p ^ j for j in 1:e], init = f) end length(f) end function nthwithndivisors(N) parray = findall(primesmask(100 * N)) for i = 1:N if isprime(i) println("$i : ", BigInt(pa...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <algorithm> #include <iomanip> #include <iostream> #include <fstream> #include <string> #include <vector> class Vector { private: double px, py, pz; public: Vector() : px(0.0), py(0.0), pz(0.0) { } Vector(double x, double y, double z) : px(x), py(y), pz(z) { } doub...
using StaticArrays, Plots, NBodySimulator const stablebodies = [MassBody(SVector(0.0, 1.0, 0.0), SVector( 5.775e-6, 0.0, 0.0), 2.0), MassBody(SVector(0.0,-1.0, 0.0), SVector(-5.775e-6, 0.0, 0.0), 2.0)] const bodies = [ MassBody(SVector(0.0, 1.0, 0.0), SVector( 5.775e-6, 0.0, 0.0), 2.0), M...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> #include <string> #include <vector> std::vector<std::string> hist; std::ostream& operator<<(std::ostream& os, const std::string& str) { return os << str.c_str(); } void appendHistory(const std::string& name) { hist.push_back(name); } void hello() { std::cout << "Hello World!\n"; ...
function input(prompt::AbstractString) print(prompt) r = readline(STDIN) if isempty(r) || r == "quit" println("bye.") elseif r == "help" println("commands: ls, cat, quit") elseif r ∈ ("ls", "cat") println("command `$r` not implemented yet") else println("Yes...?"...
Keep all operations the same but rewrite the snippet in Julia.
#include <iostream> #include <tuple> #include <vector> std::pair<int, int> tryPerm(int, int, const std::vector<int>&, int, int); std::pair<int, int> checkSeq(int pos, const std::vector<int>& seq, int n, int minLen) { if (pos > minLen || seq[0] > n) return { minLen, 0 }; else if (seq[0] == n) return ...
checksequence(pos, seq, n, minlen) = pos > minlen || seq[1] > n ? (minlen, 0) : seq[1] == n ? (pos, 1) : pos < minlen ? trypermutation(0, pos, seq, n, minlen) : (minlen, 0) function trypermutation(i, pos, seq, n, minlen) if i > pos return minlen, 0 end res1 = checksequence(pos + 1, push...
Keep all operations the same but rewrite the snippet in Julia.
#include <vector> #include <iostream> #include <fstream> #include <sstream> typedef struct { int s[4]; }userI; class jit{ public: void decode( std::string& file, std::vector<userI>& ui ) { std::ifstream f( file.c_str(), std::ios_base::in ); fileBuffer = std::string( ( std::istreambuf_iterator<...
@enum streamstate GET_FF GET_LF GET_TAB GET_CHAR ABORT chars = Dict(GET_FF => ['\f'], GET_LF => ['\n'], GET_TAB => ['\t']) function stream_decode_jit(iostream) msg, state, ffcount, lfcount, tabcount, charcount = "", GET_FF, 0, 0, 0, 0 while true if state == ABORT || eof(iostream) return msg...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <iostream> #define DEBUG(msg,...) fprintf(stderr, "[DEBUG %s@%d] " msg "\n", __FILE__, __LINE__, __VA_ARGS__) int main() { DEBUG("Hello world"); DEBUG("Some %d Things", 42); return 0; }
function test() @info "starting test()" a = [1, 2] for i in 1:4 if i > 3 @debug "debugging $a at line $(@__LINE__) of file $(@__FILE__)" else a .*= 2 end end @warn "exiting test()" println() end test() ENV["JULIA_DEBUG"] = "all" test()
Write the same algorithm in Julia as shown in this C++ implementation.
#include<iostream> #include<conio.h> using namespace std; typedef unsigned long ulong; int ith_digit_finder(long long n, long b, long i){ while(i>0){ n/=b; i--; } return (n%b); } long eeuclid(long m, long b, long *inverse){ long A1 = 1, A2 = 0, A3 = m, B1 = 0, B...
""" base 2 type Montgomery numbers """ struct Montgomery2 m::BigInt n::Int64 rrm::BigInt end function Montgomery2(x::BigInt) bitlen = length(string(x, base=2)) r = (x == 0) ? 0 : (BigInt(1) << (bitlen * 2)) % x Montgomery2(x, bitlen, r) end Montgomery2(n) = Montgomery2(BigInt(n)) function redu...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <iostream> #include <string> #include <vector> #include <queue> #include <regex> #include <tuple> #include <set> #include <array> using namespace std; class Board { public: vector<vector<char>> sData, dData; int px, py; Board(string b) { regex pattern("([^\\n]+)\\n?"); sregex_iterator end, it...
struct BoardState board::String csol::String position::Int end function move(s::BoardState, dpos) buffer = Vector{UInt8}(deepcopy(s.board)) if s.board[s.position] == '@' buffer[s.position] = ' ' else buffer[s.position] = '.' end newpos = s.position + dpos if s.board[...
Please provide an equivalent version of this C++ code in Julia.
#include <iostream"> #include <cmath> #include <vector> #include <algorithm> #include <iomanip> #include <numeric> using namespace std; const uint* binary(uint n, uint length); uint sum_subset_unrank_bin(const vector<uint>& d, uint r); vector<uint> factors(uint x); bool isPrime(uint number); bool isZum(uint n)...
using Primes function factorize(n) f = [one(n)] for (p, x) in factor(n) f = reduce(vcat, [f*p^i for i in 1:x], init=f) end f end function cansum(goal, list) if goal == 0 || list[1] == goal return true elseif length(list) > 1 if list[1] > goal return cansum(...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { s...
import Base.print mutable struct Node sub::String ch::Vector{Int} Node(str, v=Int[]) = new(str, v) end struct SuffixTree nodes::Vector{Node} function SuffixTree(s::String) nod = [Node("", Int[])] for i in 1:length(s) addSuffix!(nod, s[i:end]) end return ...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <functional> #include <iostream> #include <vector> struct Node { std::string sub = ""; std::vector<int> ch; Node() { } Node(const std::string& sub, std::initializer_list<int> children) : sub(sub) { ch.insert(ch.end(), children); } }; struct SuffixTree { s...
import Base.print mutable struct Node sub::String ch::Vector{Int} Node(str, v=Int[]) = new(str, v) end struct SuffixTree nodes::Vector{Node} function SuffixTree(s::String) nod = [Node("", Int[])] for i in 1:length(s) addSuffix!(nod, s[i:end]) end return ...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; co...
mutable struct Node edges::Dict{Char, Node} link::Union{Node, Missing} sz::Int Node() = new(Dict(), missing, 0) end sizednode(x) = (n = Node(); n.sz = x; n) function eertree(str) nodes = Vector{Node}() oddroot = sizednode(-1) evenroot = sizednode(0) oddroot.link = evenroot evenroot...
Write a version of this C++ function in Julia with identical behavior.
#include <iostream> #include <functional> #include <map> #include <vector> struct Node { int length; std::map<char, int> edges; int suffix; Node(int l) : length(l), suffix(0) { } Node(int l, const std::map<char, int>& m, int s) : length(l), edges(m), suffix(s) { } }; co...
mutable struct Node edges::Dict{Char, Node} link::Union{Node, Missing} sz::Int Node() = new(Dict(), missing, 0) end sizednode(x) = (n = Node(); n.sz = x; n) function eertree(str) nodes = Vector{Node}() oddroot = sizednode(-1) evenroot = sizednode(0) oddroot.link = evenroot evenroot...
Write the same code in Julia as shown below in C++.
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begi...
using Combinatorics clash(row2, row1::Vector{Int}) = any(i -> row1[i] == row2[i], 1:length(row2)) clash(row, rows::Vector{Vector{Int}}) = any(r -> clash(row, r), rows) permute_onefixed(i, n) = map(vec -> vcat(i, vec), permutations(filter(x -> x != i, 1:n))) filter_permuted(rows, i, n) = filter(v -> !clash(v, rows),...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <functional> #include <iostream> #include <ostream> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto it = v.cbegin(); auto end = v.cend(); os << "["; if (it != end) { os << *it; it = std::next(it); } whil...
function korasaju(g::Vector{Vector{T}}) where T<:Integer vis = falses(length(g)) L = Vector{T}(length(g)) x = length(L) + 1 t = collect(T[] for _ in eachindex(g)) function visit(u::T) if !vis[u] vis[u] = true for v in g[u] visit(v) ...
Keep all operations the same but rewrite the snippet in Julia.
#include <iomanip> #include <ctime> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <fstream> const int WID = 10, HEI = 10, MIN_WORD_LEN = 3, MIN_WORD_CNT = 25; class Cell { public: Cell() : val( 0 ), cntOverlap( 0 ) {} char val; int cntOverlap; }; class Word { public: ...
using Random const stepdirections = [[1, 0], [0, 1], [1, 1], [1, -1], [-1, 0], [0, -1], [-1, -1], [-1, 1]] const nrows = 10 const ncols = nrows const gridsize = nrows * ncols const minwords = 25 const minwordsize = 3 mutable struct LetterGrid nattempts::Int nrows::Int ncols::Int cells::Matrix{Ch...
Change the following C++ code into Julia without altering its purpose.
#include <ctime> #include <iostream> #include <algorithm> #include <fstream> #include <string> #include <vector> #include <map> class markov { public: void create( std::string& file, unsigned int keyLen, unsigned int words ) { std::ifstream f( file.c_str(), std::ios_base::in ); fileBuffer = std::str...
function markovtext(txt::AbstractString, klen::Integer, maxchlen::Integer) words = matchall(r"\w+", txt) dict = Dict() for i in 1:length(words)-klen k = join(words[i:i+klen-1], " ") v = words[i+klen] if haskey(dict, k) dict[k] = push!(dict[k], v) else ...
Please provide an equivalent version of this C++ code in Julia.
#include <algorithm> #include <iostream> #include <random> #include <vector> double uniform01() { static std::default_random_engine generator; static std::uniform_real_distribution<double> distribution(0.0, 1.0); return distribution(generator); } int bitCount(int i) { i -= ((i >> 1) & 0x55555555); ...
using GeometryTypes import Base.* CliffordVector = Point{32, Float64} e(n) = (v = zeros(32); v[(1 << n) + 1] = 1.0; CliffordVector(v)) randommultivector() = CliffordVector(rand(32)) randomvector() = sum(i -> rand() * e(i), 0:4) bitcount(n) = (count = 0; while n != 0 n &= n - 1; count += 1 end; count) function reo...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; ...
function playfair(key, txt, isencode=true, from = "J", to = "") to = (to == "" && from == "J") ? "I" : to function canonical(s, dup_toX=true) s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "") a, dupcount = [c for c in s], 0 for i in 1:2:length(a)-1 if s[i] == s...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <iostream> #include <string> using namespace std; class playfair { public: void doIt( string k, string t, bool ij, bool e ) { createGrid( k, ij ); getTextReady( t, ij, e ); if( e ) doIt( 1 ); else doIt( -1 ); display(); } private: void doIt( int dir ) { int a, b, c, d; string ntxt; ...
function playfair(key, txt, isencode=true, from = "J", to = "") to = (to == "" && from == "J") ? "I" : to function canonical(s, dup_toX=true) s = replace(replace(uppercase(s), from => to), r"[^A-Z]" => "") a, dupcount = [c for c in s], 0 for i in 1:2:length(a)-1 if s[i] == s...
Port the following code from C++ to Julia with equivalent syntax and logic.
#include <iostream> #include <iomanip> #include <string> class oo { public: void evolve( int l, int rule ) { std::string cells = "O"; std::cout << " Rule #" << rule << ":\n"; for( int x = 0; x < l; x++ ) { addNoCells( cells ); std::cout << std::setw( 40 + ( static...
function ecainfinite(cells, rule, n) notcell(cell) = (cell == '1') ? '0' : '1' rulebits = reverse(string(rule, base = 2, pad = 8)) neighbors2next = Dict(string(n - 1, base=2, pad=3) => rulebits[n] for n in 1:8) ret = String[] for i in 1:n push!(ret, cells) cells = notcell(cells[1])^2...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <algorithm> #include <iostream> #include <optional> #include <set> #include <string> #include <string_view> #include <vector> struct string_comparator { using is_transparent = void; bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } bool operato...
words = ["a", "bc", "abc", "cd", "b"] strings = ["abcd", "abbc", "abcbcd", "acdbc", "abcdd"] subregex = join(words, ")|(") regexes = ["\^\(\($subregex\)\)\{$i}\$" for i in 6:-1:1] function wordbreak() for s in strings solutions = [] for regex in regexes rmat = match(Regex(regex), s) ...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <iostream> #include <map> #include <utility> using namespace std; template<typename T> class FixedMap : private T { T m_defaultValues; public: FixedMap(T map) : T(map), m_defaultValues(move(map)){} using T::cbegin; using T::cend; using T::empty;...
using BackedUpImmutable function testBackedUpImmutableDict() fibr = BackedUpImmutableDict{String,Int64}(["a" => 0, "b" => 1, "c" => 1, "d" => 2, "e" => 3, "f" => 5, "g" => 8, "h" => 13, "i" => 21, "j" => 34, "extra" => -1]) x = fibr["extra"] @test x == -1 fibr["extra"] = 0 y = fibr["extra"...
Change the following C++ code into Julia without altering its purpose.
#include <algorithm> #include <functional> #include <iostream> #include <random> #include <vector> const auto PI = std::atan2(0, -1); bool double_equals(double a, double b, double epsilon = 0.001) { return std::abs(a - b) < epsilon; } template <typename T> bool vector_equals(const std::vector<T> & lhs, const std...
using Optim const mcclow = [-1.5, -3.0] const mccupp = [4.0, 4.0] const miclow = [0.0, 0.0] const micupp = Float64.([pi, pi]) const npar = [100, 1000] const x0 = [0.0, 0.0] michalewicz(x, m=10) = -sum(i -> sin(x[i]) * (i * sin( x[i]^2/pi))^(2*m), 1:length(x)) mccormick(x) = sin(x[1] + x[2]) + (x[1] - x[2])^2 - 1.5 *...
Generate an equivalent Julia version of this C++ code.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <sstream> #include <vector> #include <openssl/sha.h> class sha256_exception : public std::exception { public: const char* what() const noexcept override { return "SHA-256 error"; } }; class sha256 { public: sha25...
using SHA function merkletree(filename="title.png", blocksize=1024) bytes = codeunits(read(filename, String)) len = length(bytes) hsh = [sha256(view(bytes. i:min(i+blocksize-1, len)])) for i in 1:1024:len] len = length(hsh) while len > 1 hsh = [i == len ? hsh[i] : sha256(vcat(hsh[i], hsh[i ...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <functional> #include <bitset> #include <iostream> #include <cmath> using namespace std; using Z0=long long; using Z1=optional<Z0>; using Z2=optional<array<int,3>>; using Z3=function<Z2()>; const int maxUT{3000000}, dL{(int)log2(maxUT)}; struct uT{ bitset<maxUT+1>N; vector<int> G{}; array<Z3,int(dL+1)>L{Z3...
using Primes function properfactorsum(n) f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end pop!(f) return sum(f) end const maxtarget, sievelimit = 1_000_000, 512_000_000 const untouchables = ones(Bool, maxtarget) for i in 2:sievelimit n = properfac...
Rewrite this program in Julia while keeping its functionality equivalent to the C++ version.
#include <chrono> #include <iostream> #include <vector> #include <gmpxx.h> using big_int = mpz_class; big_int partitions(int n) { std::vector<big_int> p(n + 1); p[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1;; ++k) { int j = (k * (3*k - 1))/2; if (j > i) ...
using Memoize function partDiffDiff(n::Int)::Int isodd(n) ? (n+1)÷2 : n+1 end @memoize function partDiff(n::Int)::Int n<2 ? 1 : partDiff(n-1)+partDiffDiff(n-1) end @memoize function partitionsP(n::Int) T=BigInt if n<2 one(T) else psum = zero(T) for i ∈ 1:n pd =...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iomanip> #include <iostream> #include <vector> int main() { const int max_number = 100000000; std::vector<int> dsum(max_number + 1, 1); std::vector<int> dcount(max_number + 1, 1); for (int i = 2; i <= max_number; ++i) { for (int j = i + i; j <= max_number; j += i) { if (ds...
using Primes function isErdősNicolas_with_k(n) @assert n > 2 d = [one(n)] for (p, e) in eachfactor(n) d = reduce(vcat, [d * p^j for j in 1:e], init=d) end sort!(d) pop!(d) len = length(d) (len < 2 || sum(d) <= n) && return false, 0 for k in 2:len sum(@view d[1:k]) ==...
Generate an equivalent Julia version of this C++ code.
#include <iostream> #include <iomanip> #include <vector> using uint = unsigned int; std::vector<uint> divisors(uint n) { std::vector<uint> divs; for (uint d=1; d<=n/2; d++) { if (n % d == 0) divs.push_back(d); } return divs; } uint reverse(uint n) { uint r; for (r = 0; n; n /= 10) r =...
using Primes function divisors(n) f = [one(n)] for (p,e) in factor(n) f = reduce(vcat, [f*p^j for j in 1:e], init=f) end return f[1:end-1] end function isspecialdivisor(n)::Bool isprime(n) && return true nreverse = evalpoly(10, reverse(digits(n))) for d in divisors(n) dreve...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iomanip> #include <iostream> bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) ...
using Primes using Printf function isdepolignac(n::Integer) iseven(n) && return false twopows = Iterators.map(x -> 2^x, 0:floor(Int, log2(n))) return !any(twopows) do twopow isprime(n - twopow) end end function depolignacs() naturals = Iterators.countfrom() return Iterators.filter(is...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int deg...
function divrem(dividend::Vector, divisor::Vector) result = copy(dividend) quotientlen = length(divisor) - 1 for i in 1:length(dividend)-quotientlen if result[i] != 0 result[i] /= divisor[1] for j in 1:quotientlen result[i + j] -= divisor[j + 1] * result[i] ...
Generate an equivalent Julia version of this C++ code.
#include <iostream> #include <vector> #include <string> #include <cmath> std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false) { std::string r = ""; if (remainder) { r = " r: " + std::to_string(polynomial.back()); polynomial.pop_back(); } std::string formatted = ""; int deg...
function divrem(dividend::Vector, divisor::Vector) result = copy(dividend) quotientlen = length(divisor) - 1 for i in 1:length(dividend)-quotientlen if result[i] != 0 result[i] /= divisor[1] for j in 1:quotientlen result[i + j] -= divisor[j + 1] * result[i] ...
Keep all operations the same but rewrite the snippet in Julia.
#include "colorwheelwidget.h" #include <QPainter> #include <QPaintEvent> #include <cmath> namespace { QColor hsvToRgb(int h, double s, double v) { double hp = h/60.0; double c = s * v; double x = c * (1 - std::abs(std::fmod(hp, 2) - 1)); double m = v - c; double r = 0, g = 0, b = 0; if (hp <=...
using Gtk, Graphics, Colors const win = GtkWindow("Color Wheel", 450, 450) |> (const can = @GtkCanvas()) set_gtk_property!(can, :expand, true) @guarded draw(can) do widget ctx = getgc(can) h = height(can) w = width(can) center = (x = w / 2, y = h / 2) anglestep = 1/w for θ in 0:0.1:360 ...
Generate an equivalent Julia version of this C++ code.
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += " ("; ...
using Primes limitedprint(n) = (s = string(n); n = length(s); return n <= 40 ? s : s[1:20] * "..." * s[end-19:end] * " ($n digits)") function showfactorialprimes(N) for i in big"1":N f = factorial(i) isprime(f - 1) && println(lpad(i, 3), "! - 1 -> ", limitedprint(f - 1)) isprime(f + 1) && ...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include<iostream> #include<string> #include<boost/filesystem.hpp> #include<boost/format.hpp> #include<boost/iostreams/device/mapped_file.hpp> #include<optional> #include<algorithm> #include<iterator> #include<execution> #include"dependencies/xxhash.hpp" template<typename T, typename V, typename F> size_t for_each_...
using Printf, Nettle function find_duplicates(path::String, minsize::Int = 0) filesdict = Dict{String,Array{NamedTuple}}() for (root, dirs, files) in walkdir(path), fn in files filepath = joinpath(root, fn) filestats = stat(filepath) filestats.size > minsize || continue hash ...
Write the same algorithm in Julia as shown in this C++ implementation.
#include <cmath> #include <iostream> #include <vector> std::vector<int> generate_primes(int limit) { std::vector<bool> sieve(limit >> 1, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve[q >> 1] = false; ...
using Primes function primepi(N) delta = round(Int, N^0.8) return sum(i -> count(primesmask(i, min(i + delta - 1, N))), 1:delta:N) end @time for power in 0:9 println("10^", rpad(power, 5), primepi(10^power)) end
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <array> #include <iostream> using digits = std::array<unsigned int, 10>; digits get_digits(unsigned int n) { digits d = {}; do { ++d[n % 10]; n /= 10; } while (n > 0); return d; } bool same_digits(unsigned int n) { digits d = get_digits(n); for (unsigned int i = 0, m...
n = minimum([n for n in 1:2000000 if sort(digits(2n)) == sort(digits(3n)) == sort(digits(4n)) == sort(digits(5n))== sort(digits(6n))]) println("n: $n, 2n: $(2n), 3n: $(3n), 4n: $(4n), 5n: $(5n), 6n: $(6n)")
Translate this program into Julia but keep the logic exactly as in C++.
#include <array> #include <iostream> using digits = std::array<unsigned int, 10>; digits get_digits(unsigned int n) { digits d = {}; do { ++d[n % 10]; n /= 10; } while (n > 0); return d; } bool same_digits(unsigned int n) { digits d = get_digits(n); for (unsigned int i = 0, m...
n = minimum([n for n in 1:2000000 if sort(digits(2n)) == sort(digits(3n)) == sort(digits(4n)) == sort(digits(5n))== sort(digits(6n))]) println("n: $n, 2n: $(2n), 3n: $(3n), 4n: $(4n), 5n: $(5n), 6n: $(6n)")
Produce a functionally identical Julia code for the snippet given in C++.
#include <gmpxx.h> #include <primesieve.hpp> #include <iostream> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += "...
using Primes function wagstaffpair(p::Integer) isodd(p) || return (false, nothing) isprime(p) || return (false, nothing) m = (2^big(p) + 1) ÷ 3 isprime(m) || return (false, nothing) return (true, m) end function findn_wagstaff_pairs(n_to_find::T) where T <: Integer pairs = Tuple{T, BigI...
Translate this program into Julia but keep the logic exactly as in C++.
#include <gmpxx.h> #include <primesieve.hpp> #include <iostream> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += "...
using Primes function wagstaffpair(p::Integer) isodd(p) || return (false, nothing) isprime(p) || return (false, nothing) m = (2^big(p) + 1) ÷ 3 isprime(m) || return (false, nothing) return (true, m) end function findn_wagstaff_pairs(n_to_find::T) where T <: Integer pairs = Tuple{T, BigI...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * pow...
import Base.iterate, Base.IteratorSize, Base.IteratorEltype struct Palindrome x1::UInt8; x2::UInt8; outer::UInt8; end Base.IteratorSize(p::Palindrome) = Base.IsInfinite() Base.IteratorEltype(g::Palindrome) = Vector{Int8} function Base.iterate(p::Palindrome, state=(UInt8[p.x1])) arr, len = [p.outer; state; p.outer...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iostream> #include <cstdint> typedef uint64_t integer; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } class palindrome_generator { public: palindrome_generator(int digit) : power_(10), next_(digit * pow...
import Base.iterate, Base.IteratorSize, Base.IteratorEltype struct Palindrome x1::UInt8; x2::UInt8; outer::UInt8; end Base.IteratorSize(p::Palindrome) = Base.IsInfinite() Base.IteratorEltype(g::Palindrome) = Vector{Int8} function Base.iterate(p::Palindrome, state=(UInt8[p.x1])) arr, len = [p.outer; state; p.outer...
Keep all operations the same but rewrite the snippet in Julia.
#include <gmp.h> #include <iostream> using namespace std; typedef unsigned long long int u64; bool primality_pretest(u64 k) { if (!(k % 3) || !(k % 5) || !(k % 7) || !(k % 11) || !(k % 13) || !(k % 17) || !(k % 19) || !(k % 23) ) { return (k <= 23); } return true; } bool pr...
using Primes function trial_pretest(k::UInt64) if ((k % 3)==0 || (k % 5)==0 || (k % 7)==0 || (k % 11)==0 || (k % 13)==0 || (k % 17)==0 || (k % 19)==0 || (k % 23)==0) return (k <= 23) end return true end function gcd_pretest(k::UInt64) if (k <= 107) return true end ...
Convert this C++ block to Julia, preserving its control flow and logic.
#include <cstdint> #include <iostream> #include <vector> #include <primesieve.hpp> void print_diffs(const std::vector<uint64_t>& vec) { for (size_t i = 0, n = vec.size(); i != n; ++i) { if (i != 0) std::cout << " (" << vec[i] - vec[i - 1] << ") "; std::cout << vec[i]; } std::cou...
using Primes function primediffseqs(maxnum = 1_000_000) mprimes = primes(maxnum) diffs = map(p -> mprimes[p[1] + 1] - p[2], enumerate(@view mprimes[begin:end-1])) incstart, decstart, bestinclength, bestdeclength = 1, 1, 0, 0 for i in 1:length(diffs)-1 foundinc, founddec = false, false f...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> std::vector<int> generate_primes(int limit) { std::vector<bool> sieve(limit >> 1, true); for (int p = 3, s = 9; s < limit; p += 2) { if (sieve[p >> 1]) { for (int q = s; q < limit; q += p << 1) sieve...
using Primes function wilsonprimes(limit = 11000) sgn, facts = 1, accumulate(*, 1:limit, init = big"1") println(" n: Wilson primes\n--------------------") for n in 1:11 print(lpad(n, 2), ": ") sgn = -sgn for p in primes(limit) if p > n && (facts[n < 2 ? 1 : n - 1] * fa...
Convert the following code from C++ to Julia, ensuring the logic remains intact.
#include <iomanip> #include <iostream> #include <string> #include <primesieve.hpp> #include <gmpxx.h> using big_int = mpz_class; class sw_number_generator { public: sw_number_generator() { next(); } void next(); const std::string& number() const { return number_; } uint64_t prime() const { return pr...
using Primes using Printf ordi(n) = n == 1 ? "st" : n == 2 ? "nd" : "th" function SmarandacheWellin() pri = primes(12500) sw = "" pcount = 0 i = 1 println("The known Smarandache-Wellin primes are:") while pcount < 8 sw *= string(pri[i]) if isprime(parse(BigInt, sw)) ...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <iomanip> #include <iostream> #include <string> #include <primesieve.hpp> #include <gmpxx.h> using big_int = mpz_class; class sw_number_generator { public: sw_number_generator() { next(); } void next(); const std::string& number() const { return number_; } uint64_t prime() const { return pr...
using Primes using Printf ordi(n) = n == 1 ? "st" : n == 2 ? "nd" : "th" function SmarandacheWellin() pri = primes(12500) sw = "" pcount = 0 i = 1 println("The known Smarandache-Wellin primes are:") while pcount < 8 sw *= string(pri[i]) if isprime(parse(BigInt, sw)) ...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <cassert> #include <chrono> #include <iomanip> #include <iostream> #include <numeric> #include <vector> bool is_prime(unsigned int n) { assert(n > 0 && n < 64); return (1ULL << n) & 0x28208a20a08a28ac; } template <typename Iterator> bool prime_triangle_row(Iterator begin, Iterator end) { if (std:...
using Combinatorics, Primes function primetriangle(nrows::Integer) nrows < 2 && error("number of rows requested must be > 1") pmask, spinlock = primesmask(2 * (nrows + 1)), Threads.SpinLock() counts, rowstrings = [1; zeros(Int, nrows - 1)], ["" for _ in 1:nrows] for r in 2:nrows @Threads.thread...
Translate the given C++ code snippet into Julia without altering its behavior.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(int limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) ...
const SPHENIC_NUMBERS = Set{Int64}() const NOT_SPHENIC_NUMBERS = Set{Int64}() function issphenic(n::Int64) n in SPHENIC_NUMBERS && return true n in NOT_SPHENIC_NUMBERS && return false nin = n sqn = isqrt(nin) npfactors = 0 isrepeat = false i = 2 while n > 1 && !(npfactors == 0 && i >=...
Generate a Julia translation of this C++ snippet without changing its computational steps.
#include <iomanip> #include <iostream> #include <sstream> #include <utility> #include <primesieve.hpp> uint64_t digit_sum(uint64_t n) { uint64_t sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } class honaker_prime_generator { public: std::pair<uint64_t, uint64_t> next(); private:...
""" Rosetta code task: rosettacode.org/wiki/Honaker_primes """ using Formatting using Primes """ Get the sequence of Honaker primes as tuples with their primepi values first in tuple""" honaker(lim) = [(i, p) for (i, p) in enumerate(primes(lim)) if sum(digits(p)) == sum(digits(i))] println("First 50 Honaker primes:"...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b...
using Formatting import Base.iterate, Base.IteratorSize, Base.IteratorEltype, Base.Iterators.take const metallicnames = ["Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"] struct Lucas b::Int end Base.IteratorSize(s::Lucas) = Base.IsInfinite() Base.IteratorEltype(s::...
Write the same code in Julia as shown below in C++.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <iostream> const char* names[] = { "Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead" }; template<const uint N> void lucas(ulong b) { std::cout << "Lucas sequence for " << names[b] << " ratio, where b = " << b...
using Formatting import Base.iterate, Base.IteratorSize, Base.IteratorEltype, Base.Iterators.take const metallicnames = ["Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead"] struct Lucas b::Int end Base.IteratorSize(s::Lucas) = Base.IsInfinite() Base.IteratorEltype(s::...
Convert this C++ snippet to Julia and keep its semantics consistent.
#include <iostream> struct link { link* next; int data; link(int newItem, link* head) : next{head}, data{newItem}{} }; void PrintList(link* head) { if(!head) return; std::cout << head->data << " "; PrintList(head->next); } link* RemoveItem(int valueToRemove, link*&head) { for(link...
function Base.deleteat!(ll::LinkedList, index::Integer) if isempty(ll) throw(BoundsError()) end if index == 1 ll.head = ll.head.next else nd = ll.head index -= 1 while index > 1 && !isa(nd.next, EmptyNode) nd = nd.next index -= 1 end if...
Change the programming language of this snippet from C++ to Julia without modifying what it does.
#include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <numeric> #include <vector> class prime_counter { public: explicit prime_counter(int limit); int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); } private: std::vector<int> count_; }; prime_counter::prime_count...
using Primes @time let MASK = primesmask(625000) PIVEC = accumulate(+, MASK) PI(n) = n < 1 ? 0 : PIVEC[n] function Ramanujan_prime(n) maxposs = Int(ceil(4n * (log(4n) / log(2)))) for i in maxposs:-1:1 PI(i) - PI(i ÷ 2) < n && return i + 1 end ret...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <chrono> #include <cmath> #include <iomanip> #include <iostream> #include <numeric> #include <vector> class prime_counter { public: explicit prime_counter(int limit); int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); } private: std::vector<int> count_; }; prime_counter::prime_count...
using Primes @time let MASK = primesmask(625000) PIVEC = accumulate(+, MASK) PI(n) = n < 1 ? 0 : PIVEC[n] function Ramanujan_prime(n) maxposs = Int(ceil(4n * (log(4n) / log(2)))) for i in maxposs:-1:1 PI(i) - PI(i ÷ 2) < n && return i + 1 end ret...
Can you help me rewrite this code in Julia instead of C++, keeping it the same logically?
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; ...
""" julia example for rosettacode.org/wiki/Riordan_number """ using Formatting const riordans = zeros(BigInt, 10000) riordans[begin] = 1 for i in firstindex(riordans)+1:lastindex(riordans)-1 riordans[i + 1] = (i - 1) * (2 * riordans[i] + 3 * riordans[i - 1]) ÷ (i + 1) end for i in 0:31 print(rpad(format(ri...
Port the provided C++ code into Julia while preserving the original functionality.
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; ...
""" julia example for rosettacode.org/wiki/Riordan_number """ using Formatting const riordans = zeros(BigInt, 10000) riordans[begin] = 1 for i in firstindex(riordans)+1:lastindex(riordans)-1 riordans[i + 1] = (i - 1) * (2 * riordans[i] + 3 * riordans[i - 1]) ÷ (i + 1) end for i in 0:31 print(rpad(format(ri...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto...
using DataStructures function PrintContainer(iterator) iter = Iterators.Stateful(iterator) foreach(x -> print(x, ", "), Iterators.take(iter, length(iter) -1)) foreach(println, Iterators.take(iter, 1)) end function FirstFourthFifth(iterator) iter = Iterators.Stateful(iterator) foreach(x -> print(x,...
Ensure the translated Julia code behaves exactly like the original C++ snippet.
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto...
using DataStructures function PrintContainer(iterator) iter = Iterators.Stateful(iterator) foreach(x -> print(x, ", "), Iterators.take(iter, length(iter) -1)) foreach(println, Iterators.take(iter, 1)) end function FirstFourthFifth(iterator) iter = Iterators.Stateful(iterator) foreach(x -> print(x,...
Preserve the algorithm and functionality while converting the code from C++ to Julia.
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { ...
using Primes repunitprimeinbase(n, base) = isprime(evalpoly(BigInt(base), [1 for _ in 1:n])) for b in 2:40 println(rpad("Base $b:", 9), filter(n -> repunitprimeinbase(n, b), 1:2700)) end
Write the same code in Julia as shown below in C++.
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { ...
using Primes repunitprimeinbase(n, base) = isprime(evalpoly(BigInt(base), [1 for _ in 1:n])) for b in 2:40 println(rpad("Base $b:", 9), filter(n -> repunitprimeinbase(n, b), 1:2700)) end
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <algorithm> #include <cmath> #include <cstdint> #include <cstdlib> #include <cstring> #include <iostream> #include <string> #include <vector> #include <primesieve.hpp> class prime_sieve { public: explicit prime_sieve(uint64_t limit); bool is_prime(uint64_t n) const { return n == 2 || ((n & 1) ...
using Primes function maxprimebases(ndig, maxbase) maxprimebases = [Int[]] nwithbases = [0] maxprime = 10^(ndig) - 1 for p in div(maxprime + 1, 10):maxprime dig = digits(p) bases = [b for b in 2:maxbase if (isprime(evalpoly(b, dig)) && all(i -> i < b, dig))] if length(bases) > l...
Generate an equivalent Julia version of this C++ code.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> #include <map> #include <vector> #include <primesieve.hpp> class erdos_selfridge { public: explicit erdos_selfridge(int limit); uint64_t get_prime(int index) const { return primes_[index].first; } int get_category(int index); ...
using Primes primefactors(n) = collect(keys(factor(n))) function ErdösSelfridge(n) highfactors = filter(>(3), primefactors(n + 1)) category = 1 while !isempty(highfactors) highfactors = unique(reduce(vcat, [filter(>(3), primefactors(a + 1)) for a in highfactors])) category += 1 end ...
Rewrite the snippet below in Julia so it works the same as the original C++ code.
#include <primesieve.hpp> #include <chrono> #include <iomanip> #include <iostream> #include <locale> class composite_iterator { public: composite_iterator(); uint64_t next_composite(); private: uint64_t composite; uint64_t prime; primesieve::iterator pi; }; composite_iterator::composite_iterator...
using Primes function getsequencematches(N, masksize = 1_000_000_000) pmask = primesmask(masksize) found, psum, csum, pindex, cindex, pcount, ccount = 0, 2, 4, 2, 4, 1, 1 incrementpsum() = (pindex += 1; if pmask[pindex] psum += pindex; pcount += 1 end) incrementcsum() = (cindex += 1; if !pmask[cindex] ...
Produce a functionally identical Julia code for the snippet given in C++.
#include <iostream> #include <locale> #include <unordered_map> #include <primesieve.hpp> class prime_gaps { public: prime_gaps() { last_prime_ = iterator_.next_prime(); } uint64_t find_gap_start(uint64_t gap); private: primesieve::iterator iterator_; uint64_t last_prime_; std::unordered_map<uint64...
using Formatting using Primes function primegaps(limit = 10^9) c(n) = format(n, commas=true) pri = primes(limit * 5) gapstarts = Dict{Int, Int}() for i in 2:length(pri) get!(gapstarts, pri[i] - pri[i - 1], pri[i - 1]) end pm, gap1 = 10, 2 while true while !haskey(gapstarts, ...
Translate this program into Julia but keep the logic exactly as in C++.
#include <cmath> #include <iostream> #include <string> using namespace std; struct LoggingMonad { double Value; string Log; }; auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingMonad{result.Value, monad.Log + "\n" + result.Log}; } auto Root = [](doub...
struct Writer x::Real; msg::String; end Base.show(io::IO, w::Writer) = print(io, w.msg, ": ", w.x) unit(x, logmsg) = Writer(x, logmsg) bind(f, fmsg, w) = unit(f(w.x), w.msg * ", " * fmsg) f1(x) = 7x f2(x) = x + 8 a = unit(3, "after intialization") b = bind(f1, "after times 7 ", a) c = bind(f2, "after plus 8", b) ...