Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Change the following C++ code into Mathematica without altering its purpose.
#include <cstdint> #include <iomanip> #include <iostream> bool is_prime(uint64_t n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (uint64_t p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += ...
Table[With[{o = Hypergeometric2F1[(1 - n)/2, -n/2, 2, 4]}, {n, o, PrimeQ[o]}], {n, 0, 41}] // Grid
Change the following C++ code into Mathematica without altering its purpose.
#include <iostream> #include <vector> const std::vector<bool> p{ false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; bool isStrange(long n) { if (n < 10) { return false; } for (; n >= 10; n /= 10) { ...
Select[Range[101, 499], PrimeQ[Total[IntegerDigits[#][[;; 2]]]] && PrimeQ[Total[IntegerDigits[#][[2 ;;]]]] &] Length[%]
Write the same code in Mathematica as shown below in C++.
#include <iostream> #include <vector> const std::vector<bool> p{ false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; bool isStrange(long n) { if (n < 10) { return false; } for (; n >= 10; n /= 10) { ...
Select[Range[101, 499], PrimeQ[Total[IntegerDigits[#][[;; 2]]]] && PrimeQ[Total[IntegerDigits[#][[2 ;;]]]] &] Length[%]
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <iostream> #include <cstdint> using integer = uint32_t; integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; ...
ClearAll[SmarandachePrimeQ] SmarandachePrimeQ[n_Integer] := MatchQ[IntegerDigits[n], {(2 | 3 | 5 | 7) ..}] \[And] PrimeQ[n] s = Select[Range[10^5], SmarandachePrimeQ]; Take[s, UpTo[25]] s[[100]]
Write the same code in Mathematica as shown below in C++.
#include <windows.h> #include <math.h> #include <string> const int BMP_SIZE = 240, MY_TIMER = 987654; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
s = 400; Image@Table[ hue = Sin[i/16] + Sin[j/8] + Sin[(i + j)/16] + Sin[Sqrt[i^2 + j^2]/8]; hue = (hue + 4)/8; Hue[hue, 1, 0.75] , {i, 1.0, s}, {j, 1.0, s} ]
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <cstdint> #include <iostream> #include <string> using integer = uint64_t; bool square_free(integer n) { if (n % 4 == 0) return false; for (integer p = 3; p * p <= n; p += 2) { integer count = 0; for (; n % p == 0; n /= p) { if (++count > 1) return f...
squareFree[n_Integer] := DeleteCases[Last /@ FactorInteger[n], 1] === {}; findSquareFree[n__] := Select[Range[n], squareFree]; findSquareFree[45] findSquareFree[10^9, 10^9 + 145] Length[findSquareFree[10^6]]
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <array> #include <iomanip> #include <iostream> const int MC = 103 * 1000 * 10000 + 11 * 9 + 1; std::array<bool, MC + 1> SV; void sieve() { std::array<int, 10000> dS; for (int a = 9, i = 9999; a >= 0; a--) { for (int b = 9; b >= 0; b--) { for (int c = 9, s = a + b; c >= 0; c--) { ...
sum[g_] := g + Total@IntegerDigits@g ming[n_] := n - IntegerLength[n]*9 self[n_] := NoneTrue [Range[ming[n], n - 1], sum[#] == n &] Module[{t = 1, x = 1}, Reap[ While[t <= 50, If[self[x], Sow[x]; t++]; x++] ][[2, 1]]]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <cstdint> #include <iomanip> #include <iostream> uint64_t digit_sum(uint64_t n, uint64_t sum) { ++sum; while (n > 0 && n % 10 == 0) { sum -= 9; n /= 10; } return sum; } inline bool divisible(uint64_t n, uint64_t d) { if ((d & 1) == 0 && (n & 1) == 1) return false...
ClearAll[NivenQ] $HistoryLength = 0; NivenQ[n_Integer] := Divisible[n, Total[IntegerDigits[n]]] sel = Select[Range[100000000], NivenQ]; i = FoldPairList[{#2 > #1, Max[#1, #2]} &, 0, Differences[sel]]; gapindex = Range[Count[i, True]]; nivenindex = Pick[Range[Length[i]], i]; nivennumber = Pick[Most[sel], i]; gap = sel[[...
Change the following C++ code into Mathematica without altering its purpose.
#include <iostream> #include <iomanip> using namespace std; class ormConverter { public: ormConverter() : AR( 0.7112f ), CE( 0.01f ), DI( 0.0254f ), FU( 0.3048f ), KI( 1000.0f ), LI( 0.00254f ), ME( 1.0f ), MI( 7467.6f ), PI( 0.1778f ), SA( 2.1336f ), TO( 0.000254f ), VE( 0.04445f ), VR( 1066.8f ) {} ...
ClearAll[units, ConvertRussianQuantities] units = {"RussianVershoks", "RussianArshins", "RussianSazhens", "RussianVerstas", "Centimeters", "Meters", "Kilometers"}; ConvertRussianQuantities[q_Quantity] := UnitConvert[q, #] & /@ Select[units, QuantityUnit[q] != # &] ConvertRussianQuantities[Quantity[1, "Vershoks"]] Conve...
Generate an equivalent Mathematica version of this C++ code.
#include <iostream> #include <vector> constexpr int N = 2200; constexpr int N2 = 2 * N * N; int main() { using namespace std; vector<bool> found(N + 1); vector<bool> aabb(N2 + 1); int s = 3; for (int a = 1; a < N; ++a) { int aa = a * a; for (int b = 1; b < N; ++b) { ...
max = 2200; maxsq = max^2; d = Range[max]^2; Dynamic[{a, b, Length[d]}] Do[ Do[ c = Range[1, Floor[(maxsq - a^2 - b^2)^(1/2)]]; dposs = a^2 + b^2 + c^2; d = Complement[d, dposs] , {b, Floor[(maxsq - a^2)^(1/2)]} ] , {a, Floor[maxsq^(1/2)]} ] Sqrt[d]
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <array> #include <iostream> #include <vector> constexpr int MAX = 12; static std::vector<char> sp; static std::array<int, MAX> count; static int pos = 0; int factSum(int n) { int s = 0; int x = 0; int f = 1; while (x < n) { f *= ++x; s += f; } return s; } bool r(int ...
ClearAll[OverlapDistance, ConstructDistances] OverlapDistance[{s1_List, s2_List}] := OverlapDistance[s1, s2] OverlapDistance[s1_List, s2_List] := Module[{overlaprange, overlap, l}, overlaprange = {Min[Length[s1], Length[s2]], 0}; l = LengthWhile[Range[Sequence @@ overlaprange, -1], Take[s1, -#] =!= Take[s2, #] &]; ...
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <complex> #include <math.h> #include <iostream> template<class Type> struct Precision { public: static Type GetEps() { return eps; } static void SetEps(Type e) { eps = e; } private: static Type eps; }; template<class Type> Type Precision<Type>::eps = static_cast<Type>(1E-7); template<class DigT...
IntegerQ /@ {E, 2.4, 7, 9/2}
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); const uint64_t limit = 10000000000; uint64_t max_diff = 0; primesieve::iterator pi; uint64_t p1 = pi.next_prime(); for (uint64_t p = 10;;) { uint64_t p2 = pi.next_prime(); ...
Max[-Subtract @@@ Partition[Most@NestWhileList[NextPrime, 2, # < 1000000 &], 2, 1]]
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <iostream> #include <iomanip> #include <string> #include <gmpxx.h> std::string smallest_six(unsigned int n) { mpz_class pow = 1; std::string goal = std::to_string(n); while (pow.get_str().find(goal) == std::string::npos) { pow *= 6; } return pow.get_str(); } int main() {...
ClearAll[SmallestPowerContainingN] SmallestPowerContainingN[n_Integer] := Module[{i = 1, test}, While[True, test = 6^i; If[SequenceCount[IntegerDigits[test], IntegerDigits[n]] > 0, Return[{n, i, test}]]; i++; ] ] Grid[SmallestPowerContainingN /@ Range[0, 21]]
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <algorithm> #include <iostream> #include <iterator> #include <locale> #include <vector> #include "prime_sieve.hpp" const int limit1 = 1000000; const int limit2 = 10000000; class prime_info { public: explicit prime_info(int max) : max_print(max) {} void add_prime(int prime); void print(std::ostrea...
ClearAll[SafePrimeQ, UnsafePrimeQ] SafePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[(n - 1)/2] UnsafePrimeQ[n_Integer] := PrimeQ[n] \[And] ! PrimeQ[(n - 1)/2] res = {}; i = 1; While[Length[res] < 35, test = SafePrimeQ[Prime[i]]; If[test, AppendTo[res, Prime[i]]]; i++ ] res Count[Range[PrimePi[10^6]], _?(Prime /* ...
Write the same code in Mathematica as shown below in C++.
#include <iostream> #include <string> #include <vector> #include <unordered_map> using tab_t = std::vector<std::vector<std::string>>; tab_t tab1 { {"27", "Jonah"} , {"18", "Alan"} , {"28", "Glory"} , {"18", "Popeye"} , {"28", "Alan"} }; tab_t tab2 { {"Jonah", "Whales"} , {"Jonah", "Spiders"} , {"Alan", "Ghosts"...
hashJoin[table1_List,table1colindex_Integer,table2_List,table2colindex_Integer]:=Module[{h,f,t1,t2,tmp}, t1=If[table1colindex != 1,table1[[All,Prepend[Delete[Range@Length@table1[[1]],table1colindex],table1colindex]]],table1]; t2=If[table2colindex != 1, table2[[All,Prepend[Delete[Range@Length@table2[[1]],table2colindex]...
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t p = 3; ; p += 2) { ...
Select[Range[500], PrimeQ[#] && AllTrue[Subsequences[IntegerDigits[#], {1, \[Infinity]}], FromDigits /* PrimeQ] &]
Write a version of this C++ function in Mathematica with identical behavior.
#include <iostream> #include <vector> std::vector<bool> prime_sieve(size_t limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (size_t i = 4; i < limit; i += 2) sieve[i] = false; for (size_t p = 3; ; p += 2) { ...
Select[Range[500], PrimeQ[#] && AllTrue[Subsequences[IntegerDigits[#], {1, \[Infinity]}], FromDigits /* PrimeQ] &]
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <cmath> #include <cstdlib> #include <iomanip> #include <iostream> int divisor_count(int n) { int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (int p = 3; p * p <= n; p += 2) { int count = 1; for (; n % p == 0; n /= p) ++count; total *= count; ...
max = 100000; maxPrime = NextPrime[Sqrt@max, -1]; maxPower = NextPrime[Log[2, max], -1]; base = NestWhileList[NextPrime, 2, # < maxPrime &]; g = NestWhileList[NextPrime, 3, # < maxPower &] - 1; ans = Sort@Select[Flatten@Table[base^n, {n, g}], # < max &]; Labeled[Partition[Select[ans, # < 1000 &], UpTo[8]] // TableFo...
Please provide an equivalent version of this C++ code in Mathematica.
#include <cmath> #include <concepts> #include <iostream> #include <numeric> #include <optional> #include <tuple> using namespace std; optional<tuple<int, int ,int>> FindPerimeterTriplet(int perimeter) { unsigned long long perimeterULL = perimeter; auto max_M = (unsigned long long)sqrt(perimeter/2) + 1; f...
sol = First@ FindInstance[ a + b + c == 1000 && a > 0 && b > 0 && c > 0 && a^2 + b^2 == c^2, {a, b, c}, Integers]; Join[List @@@ sol, {{"Product:" , a b c /. sol}}] // TableForm
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::...
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}] treeR[1] := n tree[n_] := Flatten[treeR[n] //. {o[a_List, b_] :> (o[#, b] & /@ a), o[a_, b_List] :> (o[a, #] & /@ b)}] game24play[val_List] := Union[StringReplace[StringTake[ToString[#, InputForm], {10, -2}], "-1*" ~~ n_ :> "-" <> n] & /@ (Hold...
Write a version of this C++ function in Mathematica with identical behavior.
#include <iostream> #include <ratio> #include <array> #include <algorithm> #include <random> typedef short int Digit; constexpr Digit nDigits{4}; constexpr Digit maximumDigit{9}; constexpr short int gameGoal{24}; typedef std::array<Digit, nDigits> digitSet; digitSet d; void printTrivialOperation(std::...
treeR[n_] := Table[o[trees[a], trees[n - a]], {a, 1, n - 1}] treeR[1] := n tree[n_] := Flatten[treeR[n] //. {o[a_List, b_] :> (o[#, b] & /@ a), o[a_, b_List] :> (o[a, #] & /@ b)}] game24play[val_List] := Union[StringReplace[StringTake[ToString[#, InputForm], {10, -2}], "-1*" ~~ n_ :> "-" <> n] & /@ (Hold...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <iostream> #include <list> int main () { std::list<int> numbers {1, 5, 7, 0, 3, 2}; numbers.insert(numbers.begin(), 9); numbers.insert(numbers.end(), 4); auto it = std::next(numbers.begin(), numbers.size() / 2); numbers.insert(it, 6); for(const auto& i: numbers) std::cout <...
ds = CreateDataStructure["DoublyLinkedList"]; ds["Append", #] & /@ {1, 5, 7, 0, 3, 2}; ds["Prepend", 9]; ds["Append", 4]; ds["Append", 14]; ds["SwapPart", Round[ds["Length"]/2], ds["Length"]]; ds["Elements"]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|...
VariableNames[data_] := Module[ {TokenRemoved}, TokenRemoved = StringSplit[data,{"~And~","~Or~","~Xor~","!","(",")"}]; Union[Select[Map[StringTrim,TokenRemoved] , Not[StringMatchQ[#,""]]&]] ] TruthTable[BooleanEquation_] := Module[ {TestDataSet}, TestDataSet = MapThread[Rule,{ToExpression@VariableNames[BooleanEqua...
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <iostream> #include <stack> #include <string> #include <sstream> #include <vector> struct var { char name; bool value; }; std::vector<var> vars; template<typename T> T pop(std::stack<T> &s) { auto v = s.top(); s.pop(); return v; } bool is_operator(char c) { return c == '&' || c == '|...
VariableNames[data_] := Module[ {TokenRemoved}, TokenRemoved = StringSplit[data,{"~And~","~Or~","~Xor~","!","(",")"}]; Union[Select[Map[StringTrim,TokenRemoved] , Not[StringMatchQ[#,""]]&]] ] TruthTable[BooleanEquation_] := Module[ {TestDataSet}, TestDataSet = MapThread[Rule,{ToExpression@VariableNames[BooleanEqua...
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: R...
setcc[a_, b_] := a <= x <= b setoo[a_, b_] := a < x < b setco[a_, b_] := a <= x < b setoc[a_, b_] := a < x <= b setSubtract[s1_, s2_] := s1 && Not[s2]; inSetQ[y_, set_] := set /. x -> y set1 = setoc[0, 1] || setco[0, 2] ; Print[set1] Print["First trial set, (0, 1] ∪ [0, 2) , testing for {0,1,2}:"] Print[inSetQ[...
Write a version of this C++ function in Mathematica with identical behavior.
#include <cassert> #include <functional> #include <iostream> #define _USE_MATH_DEFINES #include <math.h> enum RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }; class RealSet { private: double low, high; double interval = 0.00001; std::function<bool(double)> predicate; public: R...
setcc[a_, b_] := a <= x <= b setoo[a_, b_] := a < x < b setco[a_, b_] := a <= x < b setoc[a_, b_] := a < x <= b setSubtract[s1_, s2_] := s1 && Not[s2]; inSetQ[y_, set_] := set /. x -> y set1 = setoc[0, 1] || setco[0, 2] ; Print[set1] Print["First trial set, (0, 1] ∪ [0, 2) , testing for {0,1,2}:"] Print[inSetQ[...
Convert the following code from C++ to Mathematica, ensuring the logic remains intact.
#include <algorithm> #include <iostream> #include <string> #include <array> #include <vector> template<typename T> T unique(T&& src) { T retval(std::move(src)); std::sort(retval.begin(), retval.end(), std::less<typename T::value_type>()); retval.erase(std::unique(retval.begin(), retval.end()), retval.end()...
letters[words_,n_] := Sort[Flatten[Characters /@ Take[words,n]]]; groupSameQ[g1_, g2_] := Sort /@ Partition[g1, 2] === Sort /@ Partition[g2, 2]; permutations[{a_, b_, c_, d_}] = Union[Permutations[{a, b, c, d}], SameTest -> groupSameQ]; Select[Flatten[permutations /@ Subsets[Union[ToLowerCase/@{"Alabama", "Alaska",...
Please provide an equivalent version of this C++ code in Mathematica.
#include <array> #include <cmath> #include <iomanip> #include <iostream> double ByVaccaSeries(int numTerms) { double gamma = 0; size_t next = 4; for(double numerator = 1; numerator < numTerms; ++numerator) { double delta = 0; for(size_t denominato...
N[EulerGamma, 1000]
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; v...
ClearAll[SuperD] SuperD[d_, m_] := Module[{n, res, num}, res = {}; n = 1; While[Length[res] < m, num = IntegerDigits[d n^d]; If[MatchQ[num, {___, Repeated[d, {d}], ___}], AppendTo[res, n] ]; n++; ]; res ] Scan[Print[SuperD[#, 10]] &, Range[2, 6]]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <iostream> #include <sstream> #include <vector> uint64_t ipow(uint64_t base, uint64_t exp) { uint64_t result = 1; while (exp) { if (exp & 1) { result *= base; } exp >>= 1; base *= base; } return result; } int main() { using namespace std; v...
ClearAll[SuperD] SuperD[d_, m_] := Module[{n, res, num}, res = {}; n = 1; While[Length[res] < m, num = IntegerDigits[d n^d]; If[MatchQ[num, {___, Repeated[d, {d}], ___}], AppendTo[res, n] ]; n++; ]; res ] Scan[Print[SuperD[#, 10]] &, Range[2, 6]]
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <iostream> #include <map> #include <cmath> int pRec(int n) { static std::map<int,int> memo; auto it = memo.find(n); if (it != memo.end()) return it->second; if (n <= 2) memo[n] = 1; else memo[n] = pRec(n-2) + pRec(n-3); return memo[n]; } int pFloor(int n) { long const double ...
ClearAll[Padovan1,a,p,s] p=N[Surd[((9+Sqrt[69])/18),3]+Surd[((9-Sqrt[69])/18),3],200]; s=1.0453567932525329623; Padovan1[nmax_Integer]:=RecurrenceTable[{a[n+1]==a[n-1]+a[n-2],a[0]==1,a[1]==1,a[2]==1},a,{n,0,nmax-1}] Padovan2[nmax_Integer]:=With[{},Floor[p^Range[-1,nmax-2]/s+1/2]] Padovan1[20] Padovan2[20] Padovan1[64]=...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <fstream> #include <iostream> #include <unordered_map> #include <vector> struct Textonym_Checker { private: int total; int elements; int textonyms; int max_found; std::vector<std::string> max_strings; std::unordered_map<std::string, std::vector<std::string>> values; int get_mappin...
ClearAll[Numerify,rls] rls={"A"->2,"B"->2,"C"->2,"D"->3,"E"->3,"F"->3,"G"->4,"H"->4,"I"->4,"J"->5,"K"->5,"L"->5,"M"->6,"N"->6,"O"->6,"P"->7,"Q"->7,"R"->7,"S"->7,"T"->8,"U"->8,"V"->8,"W"->9,"X"->9,"Y"->9,"Z"->9}; Numerify[s_String]:=Characters[ToUpperCase[s]]/.rls dict=Once[Import["http://www.rosettacode.org/wiki/Texton...
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically?
#include <iostream> #include <string> #include <windows.h> using namespace std; typedef unsigned char byte; enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR }; class fieldData { public: fieldData() : value( CLOSED ), open( false ) {} byte value; bool open, mine; }; class game { publi...
DynamicModule[{m = 6, n = 4, minecount, grid, win, reset, clear, checkwin}, reset[] := Module[{minesdata, adjacentmines}, minecount = RandomInteger[Round[{.1, .2} m*n]]; minesdata = Normal@SparseArray[# -> 1 & /@ RandomSample[Tuples[Range /@ {m, n}], minecount], {m, n}]; adjacentmines = ...
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <iostream> struct SpecialVariables { int i = 0; SpecialVariables& operator++() { this->i++; return *this; } }; int main() { SpecialVariables sv; auto sv2 = ++sv; std::cout << " sv :" << sv.i << "\n sv2:" << sv2.i << "\n...
Grid[Partition[Names["$*"],4]] -> $Aborted $ActivationGroupID $ActivationKey $ActivationUserRegistered $AddOnsDirectory $AllowDataUpdates $AllowDocumentationUpdates $AllowInternet $AssertFunction $Assump...
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsi...
ClearAll[CanonicalizeCIDR] CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change}, If[StringMatchQ[str, "*.*.*.*/*"], i = StringSplit[str, "." | "/"]; i = Interpreter["Integer"] /@ i; If[MatchQ[i, {_Integer, _Integer, _Integer, _Integer, _Integer}], If[AllTrue[i, Between[{0, 255}]], {ip,...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <cstdint> #include <iomanip> #include <iostream> #include <sstream> class ipv4_cidr { public: ipv4_cidr() {} ipv4_cidr(std::uint32_t address, unsigned int mask_length) : address_(address), mask_length_(mask_length) {} std::uint32_t address() const { return address_; } unsi...
ClearAll[CanonicalizeCIDR] CanonicalizeCIDR[str_String] := Module[{i, ip, chop, keep, change}, If[StringMatchQ[str, "*.*.*.*/*"], i = StringSplit[str, "." | "/"]; i = Interpreter["Integer"] /@ i; If[MatchQ[i, {_Integer, _Integer, _Integer, _Integer, _Integer}], If[AllTrue[i, Between[{0, 255}]], {ip,...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <cstdint> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_probably_prime(const integer& n) { return mpz_probab_prime_p(n.get_mpz_t(), 25) != 0; } bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; ...
primorials = Rest@FoldList[Times, 1, Prime[Range[500]]]; primorials = MapIndexed[{{First[#2], #1 - 1}, {First[#2], #1 + 1}} &, primorials]; Select[primorials, AnyTrue[#[[All, 2]], PrimeQ] &][[All, 1, 1]]
Generate an equivalent Mathematica version of this C++ code.
#include <boost/multiprecision/gmp.hpp> #include <iostream> using namespace boost::multiprecision; mpz_int p(uint n, uint p) { mpz_int r = 1; mpz_int k = n - p; while (n > k) r *= n--; return r; } mpz_int c(uint n, uint k) { mpz_int r = p(n, k); while (k) r /= k--; return ...
ClearAll[Combination,Permutation] Combination[n_,k_]:=Binomial[n,k] Permutation[n_,k_]:=Binomial[n,k]k! TableForm[Array[Permutation,{12,12}],TableHeadings->{Range[12],Range[12]}] TableForm[Array[Combination,{6,6},{{10,60},{10,60}}],TableHeadings->{Range[10,60,10],Range[10,60,10]}] {Row[{#,"P",#-2}," "],N@Permutation[...
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = ste...
pi[n_, prec_] := Module[{a = 1, g = N[1/Sqrt[2], prec], k, s = 0, p = 4}, For[k = 1, k < n, k++, {a, g} = {N[(a + g)/2, prec], N[Sqrt[a g], prec]}; s += p (a^2 - g^2); p += p]; N[4 a^2/(1 - s), prec]] pi[7, 100] - N[Pi, 100] 1.2026886537*10^-86 pi[7, 100] 3.14159265358979323846264338327950288419716939937...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <gmpxx.h> #include <chrono> using namespace std; using namespace chrono; void agm(mpf_class& rop1, mpf_class& rop2, const mpf_class& op1, const mpf_class& op2) { rop1 = (op1 + op2) / 2; rop2 = op1 * op2; mpf_sqrt(rop2.get_mpf_t(), rop2.get_mpf_t()); } int main(void) { auto st = ste...
pi[n_, prec_] := Module[{a = 1, g = N[1/Sqrt[2], prec], k, s = 0, p = 4}, For[k = 1, k < n, k++, {a, g} = {N[(a + g)/2, prec], N[Sqrt[a g], prec]}; s += p (a^2 - g^2); p += p]; N[4 a^2/(1 - s), prec]] pi[7, 100] - N[Pi, 100] 1.2026886537*10^-86 pi[7, 100] 3.14159265358979323846264338327950288419716939937...
Generate an equivalent Mathematica version of this C++ code.
#include <iomanip> #include <iostream> #include <list> using namespace std; void sieve(int limit, list<int> &primes) { bool *c = new bool[limit + 1]; for (int i = 0; i <= limit; i++) c[i] = false; int p = 3, n = 0; int p2 = p * p; while (p2 <= limit) { for (int i = p2; i <= limit; i += 2 * p) ...
lPrimes[n_] := Select[Range[2, n], Length[RealDigits[1/#][[1, 1]]] == # - 1 &]; lPrimes[500] Length /@ lPrimes /@ ( 250*2^Range[8])
Generate an equivalent Mathematica version of this C++ code.
using System; class Program { static int l; static int[] gp(int n) { var c = new bool[n]; var r = new int[(int)(1.28 * n)]; l = 0; r[l++] = 2; r[l++] = 3; int j, d, lim = (int)Math.Sqrt(n); for (int i = 9; i < n; i += 6) c[i] = true; for (j = 5, d = 4; j < lim; j += (d = 6 - ...
FoldList[Times, 1, Prime @ Range @ 9]
Write a version of this C++ function in Mathematica with identical behavior.
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; int...
frac[n_] /; IntegerQ[1/n] := frac[n] = {n}; frac[n_] := frac[n] = With[{p = Numerator[n], q = Denominator[n]}, Prepend[frac[Mod[-q, p]/(q Ceiling[1/n])], 1/Ceiling[1/n]]]; disp[f_] := StringRiffle[ SequenceCases[f, l : {_, 1 ...} :> If[Length[l] == 1 && l[[1]] < 1, ToString[l[[1]], Input...
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iostream> #include <optional> #include <vector> #include <string> #include <sstream> #include <boost/multiprecision/cpp_int.hpp> typedef boost::multiprecision::cpp_int integer; struct fraction { fraction(const integer& n, const integer& d) : numerator(n), denominator(d) {} integer numerator; int...
frac[n_] /; IntegerQ[1/n] := frac[n] = {n}; frac[n_] := frac[n] = With[{p = Numerator[n], q = Denominator[n]}, Prepend[frac[Mod[-q, p]/(q Ceiling[1/n])], 1/Ceiling[1/n]]]; disp[f_] := StringRiffle[ SequenceCases[f, l : {_, 1 ...} :> If[Length[l] == 1 && l[[1]] < 1, ToString[l[[1]], Input...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <iostream> #include <iomanip> #include <cmath> namespace Rosetta { template <int N> class GaussLegendreQuadrature { public: enum {eDEGREE = N}; template <typename Function> double integrate(double a, double b, Function f) { double p = (b - a) / 2...
gaussLegendreQuadrature[func_, {a_, b_}, degree_: 5] := Block[{nodes, x, weights}, nodes = Cases[NSolve[LegendreP[degree, x] == 0, x], _?NumericQ, Infinity]; weights = 2 (1 - nodes^2)/(degree LegendreP[degree - 1, nodes])^2; (b - a)/2 weights.func[(b - a)/2 nodes + (b + a)/2]] gaussLegendreQuadrature[Exp, {-3, 3}]
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
ClearAll[CutRectangle] dirs = AngleVector /@ Most[Range[0, 2 Pi, Pi/2]]; CutRectangle[nm : {n_, m_}] := Module[{start, stop, count, sols}, If[OddQ[n] \[And] OddQ[m], Return[<|"Count" -> 0, "Solutions" -> {}|>]]; start = {0, 0}; stop = nm; ClearAll[ValidPosition, ValidRoute, ProceedStep]; ValidPosition[{x_, y...
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically?
#include <array> #include <iostream> #include <stack> #include <vector> const std::array<std::pair<int, int>, 4> DIRS = { std::make_pair(0, -1), std::make_pair(-1, 0), std::make_pair(0, 1), std::make_pair(1, 0), }; void printResult(const std::vector<std::vector<int>> &v) { for (auto &row : v) {...
ClearAll[CutRectangle] dirs = AngleVector /@ Most[Range[0, 2 Pi, Pi/2]]; CutRectangle[nm : {n_, m_}] := Module[{start, stop, count, sols}, If[OddQ[n] \[And] OddQ[m], Return[<|"Count" -> 0, "Solutions" -> {}|>]]; start = {0, 0}; stop = nm; ClearAll[ValidPosition, ValidRoute, ProceedStep]; ValidPosition[{x_, y...
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <iostream> #include <vector> #include <chrono> #include <climits> #include <cmath> using namespace std; vector <long long> primes{ 3, 5 }; int main() { cout.imbue(locale("")); const int cutOff = 200, bigUn = 100000, chunks = 50, little = bigUn / chunks; const char tn[] = " cuban prime"; ...
cubans[m_Integer] := Block[{n = 1, result = {}, candidate}, While[Length[result] < m, n++; candidate = n^3 - (n - 1)^3; If[PrimeQ[candidate], AppendTo[result, candidate]]]; result] cubans[200] NumberForm[Last[cubans[100000]], NumberSeparator -> ",", DigitBlock -> 3]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
points = 5000; a = {0, 0}; b = {1, 0}; c = {0.5, 1}; d = {.7, .3}; S = {}; For[i = 1, i < points, i++, t = RandomInteger[2]; If[t == 0, d = Mean[{a, d}], If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]] Graphics[Point[S]]
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <windows.h> #include <ctime> #include <string> #include <iostream> const int BMP_SIZE = 600; class myBitmap { public: myBitmap() : pen( NULL ), brush( NULL ), clr( 0 ), wid( 1 ) {} ~myBitmap() { DeleteObject( pen ); DeleteObject( brush ); DeleteDC( hdc ); DeleteObject( bmp ); } ...
points = 5000; a = {0, 0}; b = {1, 0}; c = {0.5, 1}; d = {.7, .3}; S = {}; For[i = 1, i < points, i++, t = RandomInteger[2]; If[t == 0, d = Mean[{a, d}], If[t == 1, d = Mean[{b, d}], d = Mean[{c, d}]]]; AppendTo[S, d]] Graphics[Point[S]]
Keep all operations the same but rewrite the snippet in Mathematica.
#include <ciso646> #include <iostream> #include <regex> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include <vector> using std::vector; using std::string; #include <exception> #include <stdexcept> template <typename...Args> std::runtime_error error( Args...args ) { return st...
rpn[str_] := StringRiffle[ ToString /@ Module[{in = StringSplit[str], stack = {}, out = {}, next}, While[in != {}, next = in[[1]]; in = in[[2 ;;]]; Which[DigitQ[next], AppendTo[out, next], LetterQ[next], AppendTo[stack, next], next == ",", While[stack[[-1]] != "(", AppendTo[out, ...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
ClearAll[VisualizeGrid, Possibilities, TryRow, TryColumn] VisualizeGrid[candgrid_List] := StringRiffle[StringJoin/@Replace[candgrid,{{0}->" ",{1}->"#",{0,1}|{1,0}->"."},{2}],"\n"] Possibilities[clues_List, len_Integer] := Module[{spaces, numclue, spacecands, cands}, numclue = Length[clues]; spaces = len - Total[clu...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
template<uint _N, uint _G> class Nonogram { enum class ng_val : char {X='#',B='.',V='?'}; template<uint _NG> struct N { N() {} N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){} std::bitset<_NG> X, B, T, Tx, Tb; std::vector<int> ng; int En, gNG; void fn (con...
ClearAll[VisualizeGrid, Possibilities, TryRow, TryColumn] VisualizeGrid[candgrid_List] := StringRiffle[StringJoin/@Replace[candgrid,{{0}->" ",{1}->"#",{0,1}|{1,0}->"."},{2}],"\n"] Possibilities[clues_List, len_Integer] := Module[{spaces, numclue, spacecands, cands}, numclue = Length[clues]; spaces = len - Total[clu...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result ...
ClearAll[numerator, denominator] numerator[n_] := (2^5) ((6 n)!) (532 n^2 + 126 n + 9)/(3 (n!)^6) denominator[n_] := 10^(6 n + 3) numerator /@ Range[0, 9] val = 1/Sqrt[Total[numerator[#]/denominator[#] & /@ Range[0, 100]]]; N[val, 70]
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <boost/multiprecision/cpp_dec_float.hpp> #include <boost/multiprecision/gmp.hpp> #include <iomanip> #include <iostream> namespace mp = boost::multiprecision; using big_int = mp::mpz_int; using big_float = mp::cpp_dec_float_100; using rational = mp::mpq_rational; big_int factorial(int n) { big_int result ...
ClearAll[numerator, denominator] numerator[n_] := (2^5) ((6 n)!) (532 n^2 + 126 n + 9)/(3 (n!)^6) denominator[n_] := 10^(6 n + 3) numerator /@ Range[0, 9] val = 1/Sqrt[Total[numerator[#]/denominator[#] & /@ Range[0, 100]]]; N[val, 70]
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
palindromeQ[n_Integer] := Block[{digits = IntegerDigits[n]}, digits == Reverse@digits] nextNumber[n_Integer] := n + FromDigits[Reverse@IntegerDigits@n] lychrelQ[n_Integer] := ! palindromeQ@ Catch[Nest[If[palindromeQ[#], Throw[#], nextNumber[#]] &, nextNumber[n], 500]]
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> #include <map> #include <vector> #include <gmpxx.h> using integer = mpz_class; integer reverse(integer n) { integer rev = 0; while (n > 0) { rev = rev * 10 + (n % 10); n /= 10; } return rev; } void print_vector(const std::vector<integer>& vec) { if (vec.empty()...
palindromeQ[n_Integer] := Block[{digits = IntegerDigits[n]}, digits == Reverse@digits] nextNumber[n_Integer] := n + FromDigits[Reverse@IntegerDigits@n] lychrelQ[n_Integer] := ! palindromeQ@ Catch[Nest[If[palindromeQ[#], Throw[#], nextNumber[#]] &, nextNumber[n], 500]]
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#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 * ...
f = Compile[{{ll, _Integer}, {n, _Integer}}, Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2}, l = Abs[ll]; digitcount = Floor[Log[10, l]]; log10power = Log[10, pwr]; raised = -1; found = 0; While[found < n, raised++; firstdigits = Floor[10^(FractionalPart[lo...
Convert this C++ block to Mathematica, preserving its control flow and logic.
#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 * ...
f = Compile[{{ll, _Integer}, {n, _Integer}}, Module[{l, digitcount, log10power, raised, found, firstdigits, pwr = 2}, l = Abs[ll]; digitcount = Floor[Log[10, l]]; log10power = Log[10, pwr]; raised = -1; found = 0; While[found < n, raised++; firstdigits = Floor[10^(FractionalPart[lo...
Translate this program into Mathematica but keep the logic exactly as in C++.
#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; ...
TableForm[Array[StirlingS2, {n = 12, k = 12} + 1, {0, 0}], TableHeadings -> {"n=" <> ToString[#] & /@ Range[0, n], "k=" <> ToString[#] & /@ Range[0, k]}] Max[Abs[StirlingS2[100, #]] & /@ Range[0, 100]]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#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; ...
TableForm[Array[StirlingS2, {n = 12, k = 12} + 1, {0, 0}], TableHeadings -> {"n=" <> ToString[#] & /@ Range[0, n], "k=" <> ToString[#] & /@ Range[0, k]}] Max[Abs[StirlingS2[100, #]] & /@ Range[0, 100]]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#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...
ClearAll[FindUpToMax] FindUpToMax[max_Integer, b_Integer] := Module[{res, num}, res = {}; Do[ num = 2^u 3^v + b; If[PrimeQ[num], AppendTo[res, num]] , {u, 0, Ceiling@Log[2, max]} , {v, 0, Ceiling@Log[3, max]} ]; res //= Select[LessEqualThan[max]]; res //= Sort; res ] Print["Piermont pri...
Please provide an equivalent version of this C++ code in Mathematica.
#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 <...
ClearAll[GenerateSmoothNumbers] GenerateSmoothNumbers[max_?Positive] := GenerateSmoothNumbers[max, 7] GenerateSmoothNumbers[max_?Positive, maxprime_?Positive] := Module[{primes, len, vars, body, endspecs, its, data}, primes = Prime[Range[PrimePi[maxprime]]]; len = Length[primes]; If[max < Min[primes], {} ...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#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; ...
NextPrimeMemo[n_] := (NextPrimeMemo[n] = NextPrime[n]); PrimeList[count_] := Prime/@Range[count]; AppendPrime[list_] := Append[list,NextPrimeMemo[Last@list]]; NextCandidate[{list_, target_}] := With[ {len = Length@list, nextHead = NestWhile[Drop[#, -1] &, list, Total[#] > target &]}, Which[ {} == nextHead, {{}...
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#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) ...
TableForm[Array[StirlingS1, {n = 12, k = 12} + 1, {0, 0}], TableHeadings -> {"n=" <> ToString[#] & /@ Range[0, n], "k=" <> ToString[#] & /@ Range[0, k]}] Max[Abs[StirlingS1[100, #]] & /@ Range[0, 100]]
Port the provided C++ code into Mathematica while preserving the original functionality.
#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) ...
TableForm[Array[StirlingS1, {n = 12, k = 12} + 1, {0, 0}], TableHeadings -> {"n=" <> ToString[#] & /@ Range[0, n], "k=" <> ToString[#] & /@ Range[0, k]}] Max[Abs[StirlingS1[100, #]] & /@ Range[0, 100]]
Write a version of this C++ function in Mathematica with identical behavior.
#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; ...
ClearAll[vector,PrintVector] vector[{r_,\[Theta]_}]:=vector@@AngleVector[{r,\[Theta]}] vector[x_,y_]+vector[w_,z_]^:=vector[x+w,y+z] a_ vector[x_,y_]^:=vector[a x,a y] vector[x_,y_]-vector[w_,z_]^:=vector[x-w,y-z] PrintVector[vector[x_,y_]]:=Print["vector has first component: ",x," And second component: ",y] vector[1,...
Write the same code in Mathematica as shown below in C++.
#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 : ...
ClearAll[BurrowWheeler, InverseBurrowWheeler] BurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s}, s = Characters[bdelim <> sin <> edelim]; s = RotateLeft[s, #] & /@ Range[Length[s]]; StringJoin[LexicographicSort[s][[All, -1]]] ] InverseBurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s, chars},...
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#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 : ...
ClearAll[BurrowWheeler, InverseBurrowWheeler] BurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s}, s = Characters[bdelim <> sin <> edelim]; s = RotateLeft[s, #] & /@ Range[Length[s]]; StringJoin[LexicographicSort[s][[All, -1]]] ] InverseBurrowWheeler[sin_String, {bdelim_, edelim_}] := Module[{s, chars},...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#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,...
ClearAll[Faulhaber] bernoulliB[1] := 1/2 bernoulliB[n_] := BernoulliB[n] Faulhaber[n_, p_] := 1/(p + 1) Sum[Binomial[p + 1, j] bernoulliB[j] n^(p + 1 - j), {j, 0, p}] Table[Rest@CoefficientList[Faulhaber[n, t], n], {t, 0, 9}] // Grid Faulhaber[1000, 17]
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#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 =...
ClearAll[Faulhaber] Faulhaber[n_, 0] := n Faulhaber[n_, p_] := n^(p + 1)/(p + 1) + 1/2 n^p + Sum[BernoulliB[k]/k! p!/(p - k + 1)! n^(p - k + 1), {k, 2, p}] Table[{p, Faulhaber[n, p]}, {p, 0, 9}] // Grid
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#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...
StringForm["`` count: `` frequency: ``", Rule@@ #[[1]], StringPadLeft[ToString@ #[[2]], 8], PercentForm[N@ #[[2]]/(10^8 -1)]]& /@ Sort[Tally[Partition[Mod[Prime[Range[10^8]], 10], 2, 1]]] // Column
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#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 | ...
Addbags[configs_List] := DeleteDuplicates[ Map[LexicographicSort, Catenate[AddbagAll /@ configs], \[Infinity]]] AddbagAll[config_] := Addbag[config, #] & /@ Position[config, bag[___], \[Infinity]] Addbag[config_, pos_] := ReplacePart[config, pos -> Append[Extract[config, pos], bag[]]] With[{n = 5}, Nest[Add...
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#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[...
FromDigits[#, 2] & /@ Partition[Flatten[CellularAutomaton[30, {{1}, 0}, {200, 0}]], 8]
Translate the given C++ code snippet into Mathematica without altering its behavior.
#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...
ClearAll[GetLuckies, GetEvenLuckies] GetLuckies[max_] := Module[{luckies, f, i}, luckies = Range[1, max, 2]; f[n_] := Block[{k = luckies[[n]]}, luckies = Delete[luckies, Table[{k}, {k, k, Length@luckies, k}]]]; i = 2; While[i < Length[luckies], f[i]; i++ ]; luckies ] GetEvenLuckies[max_] := Module[...
Convert this C++ block to Mathematica, preserving its control flow and logic.
#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 ...
x:= RandomReal[1] SampleNormal[n_] := (Print[#//Length, " numbers, Mean : ", #//Mean, ", StandardDeviation : ", #//StandardDeviation]; Histogram[#, BarOrigin -> Left,Axes -> False])& [(Table[(-2*Log[x])^0.5*Cos[2*Pi*x], {n} ]] Invocation: SampleNormal[ 10000 ] ->10000 numbers, Mean : -0.0122308, StandardDeviation :...
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#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...
ClearAll[B10] B10[n_Integer] := Module[{i, out}, i = 1; While[! Divisible[FromDigits[IntegerDigits[i, 2], 10], n], i++; ]; out = FromDigits[IntegerDigits[i, 2], 10]; Row@{n, " x ", out/n, " = ", out} ] Table[B10[i], {i, Range[10]}] // Column Table[B10[i], {i, 95, 105}] // Column B10[297] B10[576] B10[594...
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#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 !...
ClearAll[WeirdNumberQ, HasSumQ] HasSumQ[n_Integer, xs_List] := HasSumHelperQ[n, ReverseSort[xs]] HasSumHelperQ[n_Integer, xs_List] := Module[{h, t}, If[Length[xs] > 0, h = First[xs]; t = Drop[xs, 1]; If[n < h, HasSumHelperQ[n, t] , n == h \[Or] HasSumHelperQ[n - h, t] \[Or] HasSumHelperQ[n, t] ...
Translate this program into Mathematica but keep the logic exactly as 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...
ClearAll[ValidSpots, VisibleByQueen, SolveQueen, GetSolution] VisualizeState[state_] := Module[{q, cells}, q = MapIndexed[If[#["q"] == -1, {}, Text[Style[#["q"], 24], #2]] &, state, {2}]; cells = MapIndexed[{If[OddQ[Total[#2]], FaceForm[], FaceForm[GrayLevel[0.8]]], EdgeForm[Black], Rectangle[#2 - 0....
Change the following C++ code into Mathematica without altering its purpose.
#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; } ...
d = Table[ Length[Divisors[n]], {n, 200000}]; t = {}; n = 0; ok = True; While[ok, n++; If[PrimeQ[n], AppendTo[t, Prime[n]^(n - 1)], c = Flatten[Position[d, n, 1, n]]; If[Length[c] >= n, AppendTo[t, c[[n]]], ok = False]]]; t
Please provide an equivalent version of this C++ code in Mathematica.
#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...
data = NBodySimulation[ "InverseSquare", {<|"Mass" -> 1, "Position" -> {0, 0}, "Velocity" -> {0, .5}|>, <|"Mass" -> 1, "Position" -> {1, 1}, "Velocity" -> {0, -.5}|>, <|"Mass" -> 1, "Position" -> {0, 1}, "Velocity" -> {0, 0}|>}, 5]; {"Time:", N[#], "Positions: ", data[All, "Position", #], "Velocities:...
Produce a functionally identical Mathematica code for the snippet given in C++.
#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)...
ClearAll[ZumkellerQ] ZumkellerQ[n_] := Module[{d = Divisors[n], t, ds, x}, ds = Total[d]; If[Mod[ds, 2] == 1, False , t = CoefficientList[Product[1 + x^i, {i, d}], x]; t[[1 + ds/2]] > 0 ] ]; i = 1; res = {}; While[Length[res] < 220, r = ZumkellerQ[i]; If[r, AppendTo[res, i]]; i++; ]...
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <functional> #include <bitset> #include <cmath> using namespace std; using Z2 = optional<long long>; using Z1 = function<Z2()>; constexpr auto pow10 = [] { array <long long, 19> n {1}; for (int j{0}, i{1}; i < 19; j = i++) n[i] = n[j] * 10; return n; } (); long long acc, l; bool izRev(int n, unsigned long l...
c = Compile[{{k, _Integer}}, Module[{out = {0}, start = 0, stop = 0, rlist = {0}, r = 0, sum = 0.0, diff = 0.0, imax = 8, step = 10}, Do[ If[j == k, imax = 2, imax = 8]; Do[ If[i == 2, start = i 10^j + 2; stop = (i + 1) 10^j - 1; step = 10; , start = i 10^j; s...
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#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...
g = Graph[{0 -> 1, 1 -> 2, 2 -> 0, 3 -> 1, 3 -> 2, 3 -> 4, 4 -> 3, 4 -> 5, 5 -> 2, 5 -> 6, 6 -> 5, 7 -> 4, 7 -> 6, 7 -> 7}]; cc = ConnectedComponents[g] Catenate[ConstantArray[Min[#], Length[#]] & /@ SortBy[cc, First]]
Translate this program into Mathematica but keep the logic exactly as in C++.
#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; ...
ClearAll[MakeTranslationTable, PlayfairCipher, PlayfairDecipher] MakeTranslationTable[tt_List] := Module[{poss, in, out}, poss = Tuples[Tuples[Range[5], 2], 2]; Table[ If[p[[1, 1]] == p[[2, 1]], {in, out} = {p, {{p[[1, 1]], Mod[p[[1, 2]] + 1, 5, 1]}, {p[[2, 1]], Mod[p[[2, 2]] + 1, 5, 1]}}}; , If...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#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; ...
ClearAll[MakeTranslationTable, PlayfairCipher, PlayfairDecipher] MakeTranslationTable[tt_List] := Module[{poss, in, out}, poss = Tuples[Tuples[Range[5], 2], 2]; Table[ If[p[[1, 1]] == p[[2, 1]], {in, out} = {p, {{p[[1, 1]], Mod[p[[1, 2]] + 1, 5, 1]}, {p[[2, 1]], Mod[p[[2, 2]] + 1, 5, 1]}}}; , If...
Write a version of this C++ function in Mathematica with identical behavior.
#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...
CellularAutomaton[18, {{1}, 0}, 15] // ArrayPlot CellularAutomaton[30, {{1}, 0}, 15] // ArrayPlot
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#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;...
a[1] = "Do not modify after creation"; a[2] = "Native demonstration"; Protect[a];
Port the provided C++ code into Mathematica while preserving the original functionality.
#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...
data=Import["https://rosettacode.org/mw/title.png","Byte"]; parts=Hash[ByteArray[#],"SHA256","ByteArray"]&/@Partition[data,UpTo[1024]]; parts=NestWhile[If[Length[#]==2,Hash[Join@@#,"SHA256","ByteArray"],First[#]]&/@Partition[#,UpTo[2]]&,parts,Length[#]>1&]; StringJoin[IntegerString[Normal[First[parts]],16]]
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#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...
f = DivisorSigma[1, #] - # &; limit = 10^5; c = Not /@ PrimeQ[Range[limit]]; slimit = 15 limit; s = ConstantArray[False, slimit + 1]; untouchable = {2, 5}; Do[ val = f[i]; If[val <= slimit, s[[val]] = True ] , {i, 6, slimit} ] Do[ If[! s[[n]], If[c[[n - 1]], If[c[[n - 3]], AppendTo[untouchable, n] ...
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#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) ...
PartitionsP /@ Range[15] PartitionsP[666] PartitionsP[6666]
Port the provided C++ code into Mathematica while preserving the original functionality.
#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 =...
SpecialDivisorQ[n_Integer] := AllTrue[Divisors[n], Divisible[IntegerReverse[n], IntegerReverse[#]] &] Select[Range[199], SpecialDivisorQ] Length[%]
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#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...
MakePolynomial[l_List, x_] := FromCoefficientRules[Thread[List /@ Range[Length[l] - 1, 0, -1] -> l], {x}] num = MakePolynomial[{1, -12, 0, -42}, x]; den = MakePolynomial[{1, -3}, x]; PolynomialQuotient[num, den, x] PolynomialRemainder[num, den, x]
Write the same code in Mathematica as shown below in C++.
#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...
MakePolynomial[l_List, x_] := FromCoefficientRules[Thread[List /@ Range[Length[l] - 1, 0, -1] -> l], {x}] num = MakePolynomial[{1, -12, 0, -42}, x]; den = MakePolynomial[{1, -3}, x]; PolynomialQuotient[num, den, x] PolynomialRemainder[num, den, x]
Convert this C++ block to Mathematica, preserving its control flow and logic.
#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 <=...
r = 100; Image[Table[ If[x^2 + y^2 <= r^2, angle = Mod[ArcTan[N@x, y]/(2 Pi), 1]; List @@ RGBColor[Hue[angle, Sqrt[x^2 + y^2]/N[r], 1.0]] , {1, 1, 1} ], {x, -r, r}, {y, -r, r}] ]
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#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_...
hash="SHA256"; minSize=Quantity[1,"Megabytes"]; allfiles=Once@Select[FileNames["*","",∞],!Once@DirectoryQ[#]&&Once@FileSize[#]>minSize&]; data={#,Once[FileHash[#,hash,All,"HexString"]]}&/@allfiles[[;;5]]; Grid[Select[GatherBy[data,Last],Length[#]>1&][[All,All,1]]]
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#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; ...
ClearAll[Phi,pi] $RecursionLimit = 10^6; Phi[x_, 0] := x Phi[x_, a_] := Phi[x, a] = Phi[x, a - 1] - Phi[Floor[x/Prime[a]], a - 1] pi[n_] := Module[{a}, If[n < 2, 0, a = pi[Floor[Sqrt[n]]]; Phi[n, a] + a - 1]] Scan[Print[pi[10^#]] &, Range[0,9]]
Translate the given C++ code snippet into Mathematica without altering its behavior.
#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...
ClearAll[GapfulQ, GetFirstPalindromicGapfulNumbers] GapfulQ[n_Integer] := Divisible[n, FromDigits[IntegerDigits[n][[{1, -1}]]]] GetFirstPalindromicGapfulNumbers[startend_, n_Integer] := Module[{out = {}, i, new, digs, id}, digs = 1; While[Length[out] < n, Do[ id = IntegerDigits[i, 10, Ceiling[digs/2]]; ...
Translate the given C++ code snippet into Mathematica without altering its behavior.
#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...
ClearAll[GapfulQ, GetFirstPalindromicGapfulNumbers] GapfulQ[n_Integer] := Divisible[n, FromDigits[IntegerDigits[n][[{1, -1}]]]] GetFirstPalindromicGapfulNumbers[startend_, n_Integer] := Module[{out = {}, i, new, digs, id}, digs = 1; While[Length[out] < n, Do[ id = IntegerDigits[i, 10, Ceiling[digs/2]]; ...