Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Convert the following code from Java to Forth, ensuring the logic remains intact.
import java.util.*; public class StrangeUniquePrimeTriplets { public static void main(String[] args) { strangeUniquePrimeTriplets(30, true); strangeUniquePrimeTriplets(1000, false); } private static void strangeUniquePrimeTriplets(int limit, boolean verbose) { boolean[] sieve = pri...
: prime? here + c@ 0= ; : notprime! here + 1 swap c! ; : prime_sieve here over erase 0 notprime! 1 notprime! dup 4 > if dup 4 do i notprime! 2 +loop then 3 begin 2dup dup * > while dup prime? if 2dup dup * do i notprime! dup 2* +loop then 2 + repeat 2drop ...
Keep all operations the same but rewrite the snippet in Forth.
import java.util.*; public class StrangeUniquePrimeTriplets { public static void main(String[] args) { strangeUniquePrimeTriplets(30, true); strangeUniquePrimeTriplets(1000, false); } private static void strangeUniquePrimeTriplets(int limit, boolean verbose) { boolean[] sieve = pri...
: prime? here + c@ 0= ; : notprime! here + 1 swap c! ; : prime_sieve here over erase 0 notprime! 1 notprime! dup 4 > if dup 4 do i notprime! 2 +loop then 3 begin 2dup dup * > while dup prime? if 2dup dup * do i notprime! dup 2* +loop then 2 + repeat 2drop ...
Port the following code from Java to Forth with equivalent syntax and logic.
public class Strange { private static final boolean[] p = { false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; public static boolean isstrange(long n) { if (n < 10) return false; ...
create isprime false , false , true , true , false , true , false , true , false , false , false , true , false , true , false , false , false , true , false , : prime? cells isprime + @ ; : strange? dup 10 < if drop false exit then begin dup 10 >= while dup 10 /mod 10 mod + prime? invert if ...
Write the same algorithm in Forth as shown in this Java implementation.
public class Strange { private static final boolean[] p = { false, false, true, true, false, true, false, true, false, false, false, true, false, true, false, false, false, true, false }; public static boolean isstrange(long n) { if (n < 10) return false; ...
create isprime false , false , true , true , false , true , false , true , false , false , false , true , false , true , false , false , false , true , false , : prime? cells isprime + @ ; : strange? dup 10 < if drop false exit then begin dup 10 >= while dup 10 /mod 10 mod + prime? invert if ...
Keep all operations the same but rewrite the snippet in Forth.
public class SmarandachePrimeDigitalSequence { public static void main(String[] args) { long s = getNextSmarandache(7); System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 "); for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) { if ( isP...
: is_prime? dup 2 < if drop false exit then dup 2 mod 0= if 2 = exit then dup 3 mod 0= if 3 = exit then 5 begin 2dup dup * >= while 2dup mod 0= if 2drop false exit then 2 + 2dup mod 0= if 2drop false exit then 4 + repeat 2drop true ; : next_prime_digit_number dup 0= if drop 2 ex...
Produce a functionally identical Forth code for the snippet given in Java.
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import static java.awt.image.BufferedImage.*; import static java.lang.Math.*; import javax.swing.*; public class PlasmaEffect extends JPanel { float[][] plasma; float hueShift = 0; BufferedImage img; public PlasmaEffect() { D...
: sqrt dup 2/ dup 0= if drop exit then begin dup >r 2dup / r> + 2/ 2dup > while nip repeat drop nip ; : sgn 0< if -1 else 1 then ; : isin 256 mod 128 - dup dup sgn * 128 swap - * negate 32 / ; ...
Rewrite this program in Forth while keeping its functionality equivalent to the Java version.
import java.util.ArrayList; import java.util.List; public class SquareFree { private static List<Long> sieve(long limit) { List<Long> primes = new ArrayList<Long>(); primes.add(2L); boolean[] c = new boolean[(int)limit + 1]; long p = 3; for (;;) { long ...
: square_free? dup 4 mod 0= if drop false exit then 3 begin 2dup dup * >= while 0 >r begin 2dup mod 0= while r> 1+ dup 1 > if 2drop drop false exit then >r tuck / swap repeat rdrop 2 + repeat 2drop true ; : print_square_free_numbers 2...
Rewrite this program in Forth while keeping its functionality equivalent to the Java version.
public class OldRussianMeasures { final static String[] keys = {"tochka", "liniya", "centimeter", "diuym", "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer", "versta", "milia"}; final static double[] values = {0.000254, 0.00254, 0.01,0.0254, 0.04445, 0.1778, 0.3048, 0....
create units s" kilometer" 2, s" meter" 2, s" centimeter" 2, s" tochka" 2, s" liniya" 2, s" diuym" 2, s" vershok" 2, s" piad" 2, s" fut" 2, s" arshin" 2, s" sazhen" 2, s" versta" 2, s" milia" 2, create values 1000.0e f, 1.0e f, 0.01e f, 0.000254e f, 0.00254e f, 0.0254e f, 0.04445e f, 0.1778e f, 0.3048e f, 0.7112e f, 2....
Rewrite this program in Forth while keeping its functionality equivalent to the Java version.
import java.util.*; public class HashJoin { public static void main(String[] args) { String[][] table1 = {{"27", "Jonah"}, {"18", "Alan"}, {"28", "Glory"}, {"18", "Popeye"}, {"28", "Alan"}}; String[][] table2 = {{"Jonah", "Whales"}, {"Jonah", "Spiders"}, {"Alan", "Ghosts"}, {"Alan...
include FMS-SI.f include FMS-SILib.f :class hash-table-m <super hash-table :m : swap drop idx @ swap false ;m :m next: last-node @ dup if begin next: dup while dup key@: @: key-addr @ key-len @ compare 0= if dup last-node ! val@: true exit then ...
Generate a Forth translation of this Java snippet without changing its computational steps.
public class PreserveScreen { public static void main(String[] args) throws InterruptedException { System.out.print("\033[?1049h\033[H"); System.out.println("Alternate screen buffer\n"); for (int i = 5; i > 0; i--) { String s = (i > 1) ? "s" : ""; System.out.printf("\...
. ." Press any key to return" ekey drop .
Rewrite the snippet below in Forth so it works the same as the original Java code.
import java.lang.reflect.Method; class Example { public int foo(int x) { return 42 + x; } } public class Main { public static void main(String[] args) throws Exception { Object example = new Example(); String name = "foo"; Class<?> clazz = example.getClass(); Method meth = clazz.getMethod(na...
include FMS-SI.f include FMS-SILib.f var x 42 x s" !:" evaluate x p: 42
Write the same algorithm in Forth as shown in this Java implementation.
import javax.swing.JFrame; import javax.swing.SwingUtilities; public class WindowExample { public static void main(String[] args) { Runnable runnable = new Runnable() { public void run() { createAndShow(); } }; SwingUtilities.invokeLater(runnable); } static void createAndShow() { ...
warnings off require xlib.fs 0 value X11-D 0 value X11-S 0 value X11-root 0 value X11-GC 0 value X11-W 0 value X11-Black 0 value X11-White 9 value X11-Top 0 value X11-Left create X11-ev 96 allot variable wm_delete : X11-D-S X11-D X11-S ; : X11-D-...
Write the same code in Forth as shown below in Java.
import java.util.LinkedList; import java.util.List; public class LongPrimes { private static void sieve(int limit, List<Integer> primes) { boolean[] c = new boolean[limit]; for (int i = 0; i < limit; i++) c[i] = false; int p = 3, n = 0; int p2 = p * p; ...
: prime? here + c@ 0= ; : notprime! here + 1 swap c! ; : sieve here over erase 0 notprime! 1 notprime! 2 begin 2dup dup * > while dup prime? if 2dup dup * do i notprime! dup +loop then 1+ repeat 2drop ; : modpow { c b a -- a^b mod c } c 1 = if 0 exit then 1 ...
Ensure the translated Forth code behaves exactly like the original Java snippet.
public class CubanPrimes { private static int MAX = 1_400_000; private static boolean[] primes = new boolean[MAX]; public static void main(String[] args) { preCompute(); cubanPrime(200, true); for ( int i = 1 ; i <= 5 ; i++ ) { int max = (int) Math.pow(10, i); ...
include ./miller-rabin.fs : d.,r >r tuck dabs <# begin 2dup 1.000 d> while # # # [char] , hold repeat #s rot sign #> r> over - spaces type ; : .,r >r s>d r> d.,r ; : sq s" dup *" evaluate ; immediate : next-cuban begin 1+ dup sq 3 * 1+ dup 3 and 0= if 2 rshift du...
Keep all operations the same but rewrite the snippet in Forth.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
#! /usr/bin/gforth require random.fs utime drop seed ! : parse-number s>number? invert throw drop ; ." width: " next-arg parse-number dup . cr CONSTANT WIDTH ." steps: " next-arg parse-number dup . cr CONSTANT STEPS ." output: " next-arg 2dup type cr 2CONSTANT OUT-FILE WIDTH 0...
Write the same code in Forth as shown below in Java.
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class ChaosGame extends JPanel { static class ColoredPoint extends Point { int colorIndex; ColoredPoint(int x, int y, int idx) { super(x, y); colorIndex = ...
#! /usr/bin/gforth require random.fs utime drop seed ! : parse-number s>number? invert throw drop ; ." width: " next-arg parse-number dup . cr CONSTANT WIDTH ." steps: " next-arg parse-number dup . cr CONSTANT STEPS ." output: " next-arg 2dup type cr 2CONSTANT OUT-FILE WIDTH 0...
Translate this program into Forth but keep the logic exactly as in Java.
import java.util.Stack; public class ShuntingYard { public static void main(String[] args) { String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; System.out.printf("infix: %s%n", infix); System.out.printf("postfix: %s%n", infixToPostfix(infix)); } static String infixToPostfix(String ...
with: n { "+" : 2, "-" : 2, "/" : 3, "*" : 3, "^" : -4, "" : -1 } var, tokens : precedence tokens @ over m:@ nip null? if drop 0 then ; var ops var out : >out out @ swap a:push drop ; : >ops 2 a:close ops @ swap a:push drop ; : a:peek -1 a:@ ; : pop-ops a:len not if ;...
Port the provided Java code into Forth while preserving the original functionality.
import java.util.Locale; public class Test { public static void main(String[] args) { System.out.println(new Vec2(5, 7).add(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).sub(new Vec2(2, 3))); System.out.println(new Vec2(5, 7).mult(11)); System.out.println(new Vec2(5, 7).div(2...
: v. swap . . ; : v* swap over * >r * r> ; : v/ swap over / >r / r> ; : v+ >r swap >r + r> r> + ; : v- >r swap >r - r> r> - ;
Ensure the translated Forth code behaves exactly like the original Java snippet.
import java.awt.*; import java.awt.event.ActionEvent; import java.util.*; import javax.swing.*; import javax.swing.Timer; public class Perceptron extends JPanel { class Trainer { double[] inputs; int answer; Trainer(double x, double y, int a) { inputs = new double[]{x, y, 1}; ...
require random.fs here seed ! warnings off : randomWeight 2000 random 1000 - s>f 1000e f/ ; : createPerceptron create dup , 0 ?DO randomWeight f, LOOP ; variable arity variable ^weights variable ^inputs : perceptron! dup @ arity ! cell+ ^weights ! ; : inputs! ^inputs ! ; 0.0001e fconstan...
Translate this program into Forth but keep the logic exactly as in Java.
import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Random; import java.util.Scanner; public class csprngBBS { public static Scanner input = new Scann...
require random.fs : prngimage outfile-id >r s" prngimage.pbm" w/o create-file throw to outfile-id s 500 0 do 500 0 do 2 random 48 + emit loop #lf emit loop outfile-id close-file throw r> to outfile-id ; prngimage
Produce a functionally identical Forth code for the snippet given in Java.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str...
CREATE BUF 0 , : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : GETINT >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ; : GETN...
Translate this program into Forth but keep the logic exactly as in Java.
import java.util.Scanner; import java.io.File; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.HashMap; class Interpreter { static Map<String, Integer> globals = new HashMap<>(); static Scanner s; static List<Node> list = new ArrayList<>(); static Map<String, NodeType> str...
CREATE BUF 0 , : PEEK BUF @ 0= IF KEY BUF ! THEN BUF @ ; : GETC PEEK 0 BUF ! ; : SPACE? DUP BL = SWAP 9 14 WITHIN OR ; : >SPACE BEGIN PEEK SPACE? WHILE GETC DROP REPEAT ; : DIGIT? 48 58 WITHIN ; : GETINT >SPACE 0 BEGIN PEEK DIGIT? WHILE GETC [CHAR] 0 - SWAP 10 * + REPEAT ; : GETN...
Keep all operations the same but rewrite the snippet in Mathematica.
std::cout << "Tür\n"; std::cout << "T\u00FC\n";
Markup : () Sequence {} List " String \ Escape for following character Comment block base^^number`s ` Context [[]] Indexed reference Within expression: \ At end of line: Continue on next line, skipping white space
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; ...
Select[Range[500], AnyTrue[IntegerDigits[#, 16], GreaterEqualThan[10]] &]
Write the same code in Mathematica as shown below in C++.
#include <iomanip> #include <iostream> bool nondecimal(unsigned int n) { for (; n > 0; n >>= 4) { if ((n & 0xF) > 9) return true; } return false; } int main() { unsigned int count = 0; for (unsigned int n = 0; n < 501; ++n) { if (nondecimal(n)) { ++count; ...
Select[Range[500], AnyTrue[IntegerDigits[#, 16], GreaterEqualThan[10]] &]
Write the same code in Mathematica as shown below in C++.
#include <cassert> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> using big_int = mpz_class; auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else ...
next[n_Integer] := If[EvenQ@n, Floor[Sqrt[n]], Floor[n^(3/2)]] stats[n_Integer] := Block[{data = Most@NestWhileList[next, n, # > 1 &], mx}, mx = First@Ordering[data, -1]; {n, Length[data], data[[mx]], mx - 1}] {TableForm[Table[stats@n, {n, 20, 39}], TableHeadings -> {None, {"n", "length", "max", "max pos"}...
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <cassert> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> using big_int = mpz_class; auto juggler(int n) { assert(n >= 1); int count = 0, max_count = 0; big_int a = n, max = n; while (a != 1) { if (a % 2 == 0) a = sqrt(a); else ...
next[n_Integer] := If[EvenQ@n, Floor[Sqrt[n]], Floor[n^(3/2)]] stats[n_Integer] := Block[{data = Most@NestWhileList[next, n, # > 1 &], mx}, mx = First@Ordering[data, -1]; {n, Length[data], data[[mx]], mx - 1}] {TableForm[Table[stats@n, {n, 20, 39}], TableHeadings -> {None, {"n", "length", "max", "max pos"}...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <time.h> #include <iostream> #include <string> #include <iomanip> #include <cstdlib> typedef unsigned int uint; using namespace std; enum movDir { UP, DOWN, LEFT, RIGHT }; class tile { public: tile() : val( 0 ), blocked( false ) {} uint val; bool blocked; }; class g2048 { public: g2048() : d...
SetOptions[InputNotebook[],NotebookEventActions->{ "LeftArrowKeyDown":>(stat=Coalesce[stat];AddNew[]), "RightArrowKeyDown":>(stat=Reverse/@Coalesce[Reverse/@stat];AddNew[]), "UpArrowKeyDown":>(stat=Coalesce[stat\[Transpose]]\[Transpose];AddNew[]), "DownArrowKeyDown":>(stat=(Reverse/@(Coalesce[Reverse/@(stat\[Transpose]...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> void reverse(std::istream& in, std::ostream& out) { constexpr size_t record_length = 80; char record[record_length]; while (in.read(record, record_length)) { std::reverse(std::begin(record), std::end(record)); ou...
FixedRecordReverse[inFile_File, outFile_File, length_ : 80] := Module[{inStream, outStream, line, byte}, WithCleanup[ inStream = OpenRead[inFile, BinaryFormat -> True]; outStream = OpenWrite[outFile, BinaryFormat -> True]; , While[True, line = {}; Do[ byte = BinaryR...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <cstdlib> #include <fstream> #include <iostream> int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot open file '" << filename << "'.\n"; return EXIT_FAILURE; } std::string w...
dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]]; dict //= StringSplit[#, "\n"] &; dict //= Select[StringLength /* GreaterThan[5]]; Select[dict, StringTake[#, 3] === StringTake[#, -3] &]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <iostream> using namespace std; class Cuboid { private: double length; double breadth; double height; public: double getVolume(void) { return length * breadth * height; } void setLength( double l ) { length = l; } vo...
vec[{a_, b_}] + vec[{c_, d_}] ^:= vec[{a + c, b + d}] vec[{4, 7}] + vec[{9, 3}]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <bitset> #include <cctype> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <string> #include <vector> size_t consonants(const std::string& word) { std::bitset<26> bits; size_t bit = 0; for (char ch : word) { ch = std::tolower(static_ca...
consonants = DeleteCases[Alphabet[], Alternatives @@ Characters["euioa"]]; dict = Once[Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]]; dict //= StringSplit[#, "\n"] &; dict //= Select[StringLength /* GreaterThan[10]]; dict = {#, Select[Characters[#], MemberQ[con...
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <set> #include <string> #include <utility> #include <vector> using word_list = std::vector<std::pair<std::string, std::string>>; void print_words(std::ostream& out, const word_list& words) { int n = 1; for (const auto& pair ...
dict = Import["https://web.archive.org/web/20180611003215/http://www.puzzlers.org/pub/wordlists/unixdict.txt"]; dict //= StringSplit[#, "\n"] &; ClearAll[OddLetters, OddWordQ] OddLetters[s_String] := StringTake[s, {1, -1, 2}] OddWordQ[s_String] := Module[{}, If[StringLength[s] >= 9, MemberQ[dict, OddLetters[s]] ...
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas...
ClearAll[Jacobsthal, JacobsthalLucas, JacobsthalOblong] Jacobsthal[n_]:=(2^n-(-1)^n)/3 JacobsthalLucas[n_]:=2^n+(-1)^n JacobsthalOblong[n_]:=Jacobsthal[n]Jacobsthal[n+1] Jacobsthal[Range[0, 29]] JacobsthalLucas[Range[0, 29]] JacobsthalOblong[Range[0, 19]] n=0; i=0; Reap[While[n<20, If[ PrimeQ[Jacobsthal[i]] , Sow...
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <gmpxx.h> #include <iomanip> #include <iostream> using big_int = mpz_class; bool is_probably_prime(const big_int& n) { return mpz_probab_prime_p(n.get_mpz_t(), 30) != 0; } big_int jacobsthal_number(unsigned int n) { return ((big_int(1) << n) - (n % 2 == 0 ? 1 : -1)) / 3; } big_int jacobsthal_lucas...
ClearAll[Jacobsthal, JacobsthalLucas, JacobsthalOblong] Jacobsthal[n_]:=(2^n-(-1)^n)/3 JacobsthalLucas[n_]:=2^n+(-1)^n JacobsthalOblong[n_]:=Jacobsthal[n]Jacobsthal[n+1] Jacobsthal[Range[0, 29]] JacobsthalLucas[Range[0, 29]] JacobsthalOblong[Range[0, 19]] n=0; i=0; Reap[While[n<20, If[ PrimeQ[Jacobsthal[i]] , Sow...
Write the same code in Mathematica as shown below in C++.
#include <iostream> #include <cstdint> #include <vector> #include "prime_sieve.hpp" using integer = uint32_t; using vector = std::vector<integer>; void print_vector(const vector& vec) { if (!vec.empty()) { auto i = vec.begin(); std::cout << '(' << *i; for (++i; i != vec.end(); ++i) ...
ClearAll[Primediffs] p = Prime[Range[PrimePi[10^6]]]; Primediffs[seq_] := {First[#], Last[#], Length[#]} &[p[[#1 ;; #2 + 1]] & @@@ SequencePosition[Differences[p], seq]] Primediffs[{2}] Primediffs[{1}] Primediffs[{2, 2}] Primediffs[{2, 4}] Primediffs[{4, 2}] Primediffs[{6, 4, 2}]
Can you help me rewrite this code in Mathematica instead of C++, keeping it the same logically?
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n"; }
Prime[10001]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <iostream> #include <locale> #include <primesieve.hpp> int main() { std::cout.imbue(std::locale("")); std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n"; }
Prime[10001]
Translate this program into Mathematica but keep the logic exactly as in C++.
#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; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; ...
p = Prime[Range[PrimePi[1000]]]; TableForm[ Select[Transpose[{Range[Length[p]], p, Accumulate[p]}], Last /* PrimeQ], TableHeadings -> {None, {"Prime count", "Prime", "Prime sum"}} ]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#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; } int i = 5; while (i * i <= n) { if (n % i == 0) { return false; } i += 2; ...
p = Prime[Range[PrimePi[1000]]]; TableForm[ Select[Transpose[{Range[Length[p]], p, Accumulate[p]}], Last /* PrimeQ], TableHeadings -> {None, {"Prime count", "Prime", "Prime sum"}} ]
Write the same code in Mathematica as shown below in C++.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
Max@Select[FromDigits/@Rest@Flatten[Permutations/@Subsets[Range@9,9],1],And@@IntegerQ/@(#/IntegerDigits@#)&]
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#include <iostream> #include <sstream> #include <set> bool checkDec(int num) { std::set<int> set; std::stringstream ss; ss << num; auto str = ss.str(); for (int i = 0; i < str.size(); ++i) { char c = str[i]; int d = c - '0'; if (d == 0) return false; if (num % d !=...
Max@Select[FromDigits/@Rest@Flatten[Permutations/@Subsets[Range@9,9],1],And@@IntegerQ/@(#/IntegerDigits@#)&]
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t...
TableForm[Table[JacobiSymbol[n, k], {n, 1, 17, 2}, {k, 16}], TableHeadings -> {ReplacePart[Range[1, 17, 2], 1 -> "n=1"], ReplacePart[Range[16], 1 -> "k=1"]}]
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <algorithm> #include <cassert> #include <iomanip> #include <iostream> int jacobi(int n, int k) { assert(k > 0 && k % 2 == 1); n %= k; int t = 1; while (n != 0) { while (n % 2 == 0) { n /= 2; int r = k % 8; if (r == 3 || r == 5) t = -t...
TableForm[Table[JacobiSymbol[n, k], {n, 1, 17, 2}, {k, 16}], TableHeadings -> {ReplacePart[Range[1, 17, 2], 1 -> "n=1"], ReplacePart[Range[16], 1 -> "k=1"]}]
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> #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) { os << ", " << *i...
Permanent[m_List] := With[{v = Array[x, Length[m]]}, Coefficient[Times @@ (m.v), Times @@ v] ]
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <iostream> #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) { os << ", " << *i...
Permanent[m_List] := With[{v = Array[x, Length[m]]}, Coefficient[Times @@ (m.v), Times @@ v] ]
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <gmpxx.h> #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; ...
ClearAll[DeceptiveNumberQ] DeceptiveNumberQ[n_Integer] := If[! PrimeQ[n], PowerMod[10, n - 1, 9 n] == 1] c = 0; out = Reap[Do[ If[DeceptiveNumberQ[i], Sow[i]; c++; If[c >= 1000, Break[]] ] , {i, 2, \[Infinity]} ]][[2, 1]]; Print["The first 100:"] Multicolumn[Take[out, 100], A...
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <gmpxx.h> #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; ...
ClearAll[DeceptiveNumberQ] DeceptiveNumberQ[n_Integer] := If[! PrimeQ[n], PowerMod[10, n - 1, 9 n] == 1] c = 0; out = Reap[Do[ If[DeceptiveNumberQ[i], Sow[i]; c++; If[c >= 1000, Break[]] ] , {i, 2, \[Infinity]} ]][[2, 1]]; Print["The first 100:"] Multicolumn[Take[out, 100], A...
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout ...
ClearAll[SumAsSubString] SumAsSubString[n_Integer] := Module[{id, s}, id = IntegerDigits[n]; s = Total[id]; SequenceCount[id, IntegerDigits[s]] > 0 ] Select[Range[999], SumAsSubString]
Write the same code in Mathematica as shown below in C++.
#include <iostream> int digitSum(int n) { int s = 0; do {s += n % 10;} while (n /= 10); return s; } int main() { for (int i=0; i<1000; i++) { auto s_i = std::to_string(i); auto s_ds = std::to_string(digitSum(i)); if (s_i.find(s_ds) != std::string::npos) { std::cout ...
ClearAll[SumAsSubString] SumAsSubString[n_Integer] := Module[{id, s}, id = IntegerDigits[n]; s = Total[id]; SequenceCount[id, IntegerDigits[s]] > 0 ] Select[Range[999], SumAsSubString]
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <cstdint> #include <iostream> #include <string> #include <primesieve.hpp> void print_twin_prime_count(long long limit) { std::cout << "Number of twin prime pairs less than " << limit << " is " << (limit > 0 ? primesieve::count_twins(0, limit - 1) : 0) << '\n'; } int main(int argc, char** argv) { ...
ClearAll[TwinPrimeCount] TwinPrimeCount[mx_] := Module[{pmax, min, max, total}, pmax = PrimePi[mx]; total = 0; Do[ min = 10^6 i; min = Max[min, 1]; max = 10^6 (i + 1); max = Min[max, pmax]; total += Count[Differences[Prime[Range[min, max]]], 2] , {i, 0, Ceiling[pmax/10^6]} ]; total ] Do...
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
brazilianQ[n_Integer /; n>6 ] := AnyTrue[ Range[2, n-2], MatchQ[IntegerDigits[n, #], {x_ ...}] & ] Select[Range[100], brazilianQ, 20] Select[Range[100], brazilianQ@# && OddQ@# &, 20] Select[Range[10000], brazilianQ@# && PrimeQ@# &, 20]
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <iostream> bool sameDigits(int n, int b) { int f = n % b; while ((n /= b) > 0) { if (n % b != f) { return false; } } return true; } bool isBrazilian(int n) { if (n < 7) return false; if (n % 2 == 0)return true; for (int b = 2; b < n - 1; b++) { ...
brazilianQ[n_Integer /; n>6 ] := AnyTrue[ Range[2, n-2], MatchQ[IntegerDigits[n, #], {x_ ...}] & ] Select[Range[100], brazilianQ, 20] Select[Range[100], brazilianQ@# && OddQ@# &, 20] Select[Range[10000], brazilianQ@# && PrimeQ@# &, 20]
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
ClearAll[f] f[s_List] := Block[{a = s[[-1]], len = Length@s}, Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70] g = Nest[f, {0}, 70]; Take[g, 15] p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]] p = Flatten[Position[g, #]] & /@ p; TakeSmallestBy[p, Last, 1][[1]]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <iostream> #include <ostream> #include <set> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { auto i = v.cbegin(); auto e = v.cend(); os << '['; if (i != e) { os << *i; i = std::next(i); } while (i != e) { ...
ClearAll[f] f[s_List] := Block[{a = s[[-1]], len = Length@s}, Append[s, If[a > len && ! MemberQ[s, a - len], a - len, a + len]]]; g = Nest[f, {0}, 70] g = Nest[f, {0}, 70]; Take[g, 15] p = Select[Tally[g], Last /* EqualTo[2]][[All, 1]] p = Flatten[Position[g, #]] & /@ p; TakeSmallestBy[p, Last, 1][[1]]
Keep all operations the same but rewrite the snippet in Mathematica.
#include <iostream> #include <functional> template <typename F> struct RecursiveFunc { std::function<F(RecursiveFunc)> o; }; template <typename A, typename B> std::function<B(A)> Y (std::function<std::function<B(A)>(std::function<B(A)>)> f) { RecursiveFunc<std::function<B(A)>> r = { std::function<std::function<B(...
Y = Function[f, #[#] &[Function[g, f[g[g][##] &]]]]; factorial = Y[Function[f, If[# < 1, 1, # f[# - 1]] &]]; fibonacci = Y[Function[f, If[# < 2, #, f[# - 1] + f[# - 2]] &]];
Translate this program into Mathematica but keep the logic exactly as in C++.
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return s...
ClearAll[FactorionQ] FactorionQ[n_,b_:10]:=Total[IntegerDigits[n,b]!]==n Select[Range[1500000],FactorionQ[#,9]&] Select[Range[1500000],FactorionQ[#,10]&] Select[Range[1500000],FactorionQ[#,11]&] Select[Range[1500000],FactorionQ[#,12]&]
Write a version of this C++ function in Mathematica with identical behavior.
#include <iostream> class factorion_t { public: factorion_t() { f[0] = 1u; for (uint n = 1u; n < 12u; n++) f[n] = f[n - 1] * n; } bool operator()(uint i, uint b) const { uint sum = 0; for (uint j = i; j > 0u; j /= b) sum += f[j % b]; return s...
ClearAll[FactorionQ] FactorionQ[n_,b_:10]:=Total[IntegerDigits[n,b]!]==n Select[Range[1500000],FactorionQ[#,9]&] Select[Range[1500000],FactorionQ[#,10]&] Select[Range[1500000],FactorionQ[#,11]&] Select[Range[1500000],FactorionQ[#,12]&]
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0;...
DivisorSigma[1, Range[100]]
Write a version of this C++ function in Mathematica with identical behavior.
#include <iomanip> #include <iostream> unsigned int divisor_sum(unsigned int n) { unsigned int total = 1, power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) total += power; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int sum = 1; for (power = p; n % p == 0;...
DivisorSigma[1, Range[100]]
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <algorithm> #include <iostream> #include <vector> using namespace std; bool InteractiveCompare(const string& s1, const string& s2) { if(s1 == s2) return false; static int count = 0; string response; cout << "(" << ++count << ") Is " << s1 << " < " << s2 << "? "; getline(cin, response); ...
ClearAll[HumanOrderCheck] HumanOrderCheck[opt1_,opt2_]:=ChoiceDialog[Row@{"Is {",opt1,", ", opt2, "} ordered?"},{"Yes"->True,"No"->False}] Sort[{"violet","red","green","indigo","blue","yellow","orange"},HumanOrderCheck]
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <iostream> #include <vector> #include <boost/integer/common_factor.hpp> #include <boost/multiprecision/cpp_int.hpp> #include <boost/multiprecision/miller_rabin.hpp> typedef boost::multiprecision::cpp_int integer; integer fermat(unsigned int n) { unsigned int p = 1; for (unsigned int i = 0; i < n; ++i...
ClearAll[Fermat] Fermat[n_] := 2^(2^n) + 1 Fermat /@ Range[0, 9] Scan[FactorInteger /* Print, %]
Please provide an equivalent version of this C++ code in Mathematica.
#include <iostream> #include <vector> using std::cout; using std::vector; void distribute(int dist, vector<int> &List) { if (dist > List.size() ) List.resize(dist); for (int i=0; i < dist; i++) List[i]++; } vector<int> beadSort(int *myints, int n) { vector<int> list, list2, fifth ...
beadsort[ a ] := Module[ { m, sorted, s ,t }, sorted = a; m = Max[a]; t=ConstantArray[0, {m,m} ]; If[ Min[a] < 0, Print["can't sort"]]; For[ i = 1, i < Length[a], i++, t[[i,1;;a[[i]]]]=1 ] For[ i = 1 ,i <= m, i++, s = Total[t[[;;,i]]]; t[[ ;; , i]] = 0; t[[1 ;; s , i]] = 1; ] For[ i=1,i<=Length[a],i++, sorted[[i]] ...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ...
Co9[n_, b_: 10] := With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]}, If[ans == b - 1, 0, ans]];
Generate an equivalent Mathematica version of this C++ code.
#include <iostream> int main() { int Base = 10; const int N = 2; int c1 = 0; int c2 = 0; for (int k=1; k<pow((double)Base,N); k++){ c1++; if (k%(Base-1) == (k*k)%(Base-1)){ c2++; std::cout << k << " "; } } std::cout << "\nTrying " << c2 << " numbers instead of " << c1 << " numbers saves " << 100 ...
Co9[n_, b_: 10] := With[{ans = FixedPoint[Total@IntegerDigits[#, b] &, n]}, If[ans == b - 1, 0, ans]];
Preserve the algorithm and functionality while converting the code from C++ to Mathematica.
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; ...
DivisorSum[#, 1 &] & /@ Range[100]
Port the provided C++ code into Mathematica while preserving the original functionality.
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; ...
DivisorSum[#, 1 &] & /@ Range[100]
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <iomanip> #include <iostream> #include <vector> constexpr int MU_MAX = 1'000'000; std::vector<int> MU; int mobiusFunction(int n) { if (!MU.empty()) { return MU[n]; } MU.resize(MU_MAX + 1, 1); int root = sqrt(MU_MAX); for (int i = 2; i <= root; i++) { if (MU[i] == 1)...
Grid[Partition[MoebiusMu[Range[99]], UpTo[10]]]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod;...
ClearAll[CurzonNumberQ] CurzonNumberQ[b_Integer][n_Integer]:=PowerMod[b,n,b n+1]==b n val=Select[Range[100000],CurzonNumberQ[2]]; Take[val,50] val[[1000]] val=Select[Range[100000],CurzonNumberQ[4]]; Take[val,50] val[[1000]] val=Select[Range[100000],CurzonNumberQ[6]]; Take[val,50] val[[1000]] val=Select[Range[100000]...
Change the following C++ code into Mathematica without altering its purpose.
#include <cstdint> #include <iomanip> #include <iostream> #include <vector> uint64_t modpow(uint64_t base, uint64_t exp, uint64_t mod) { if (mod == 1) return 0; uint64_t result = 1; base %= mod; for (; exp > 0; exp >>= 1) { if ((exp & 1) == 1) result = (result * base) % mod;...
ClearAll[CurzonNumberQ] CurzonNumberQ[b_Integer][n_Integer]:=PowerMod[b,n,b n+1]==b n val=Select[Range[100000],CurzonNumberQ[2]]; Take[val,50] val[[1000]] val=Select[Range[100000],CurzonNumberQ[4]]; Take[val,50] val[[1000]] val=Select[Range[100000],CurzonNumberQ[6]]; Take[val,50] val[[1000]] val=Select[Range[100000]...
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iomanip> #include <iostream> #include <vector> std::vector<int> mertens_numbers(int max) { std::vector<int> m(max + 1, 1); for (int n = 2; n <= max; ++n) { for (int k = 2; k <= n; ++k) m[n] -= m[n / k]; } return m; } int main() { const int max = 1000; auto m(merte...
ClearAll[Mertens] Mertens[n_] := Total[MoebiusMu[Range[n]]] Grid[Partition[Mertens /@ Range[99], UpTo[10]]] Count[Mertens /@ Range[1000], 0] SequenceCount[Mertens /@ Range[1000], {Except[0], 0}]
Translate the given C++ code snippet into Mathematica without altering its behavior.
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ...
Divisors/*Apply[Times] /@ Range[50]
Transform the following C++ implementation into Mathematica, maintaining the same output and logic.
#include <cmath> #include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ...
Divisors/*Apply[Times] /@ Range[50]
Write the same code in Mathematica as shown below in C++.
#include <cstdint> #include <iomanip> #include <iostream> #include <set> #include <primesieve.hpp> class erdos_prime_generator { public: erdos_prime_generator() {} uint64_t next(); private: bool erdos(uint64_t p) const; primesieve::iterator iter_; std::set<uint64_t> primes_; }; uint64_t erdos_prim...
ClearAll[ErdosPrimeQ] ErdosPrimeQ[p_Integer] := Module[{k}, If[PrimeQ[p], k = 1; While[k! < p, If[PrimeQ[p - k!], Return[False]]; k++; ]; True , False ] ] sel = Select[Range[2500], ErdosPrimeQ] Length[sel] sel = Select[Range[999999], ErdosPrimeQ]; {Length[sel], Last[sel]}
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <cstdint> #include <iomanip> #include <iostream> #include <set> #include <primesieve.hpp> class erdos_prime_generator { public: erdos_prime_generator() {} uint64_t next(); private: bool erdos(uint64_t p) const; primesieve::iterator iter_; std::set<uint64_t> primes_; }; uint64_t erdos_prim...
ClearAll[ErdosPrimeQ] ErdosPrimeQ[p_Integer] := Module[{k}, If[PrimeQ[p], k = 1; While[k! < p, If[PrimeQ[p - k!], Return[False]]; k++; ]; True , False ] ] sel = Select[Range[2500], ErdosPrimeQ] Length[sel] sel = Select[Range[999999], ErdosPrimeQ]; {Length[sel], Last[sel]}
Generate a Mathematica translation of this C++ snippet without changing its computational steps.
#include <deque> #include <algorithm> #include <ostream> #include <iterator> namespace cards { class card { public: enum pip_type { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace, pip_count }; enum suite_type { hearts, spades, diamonds, clubs, suite_count }; ...
MakeDeck[] := Tuples[{{"Ace ", 2, 3 , 4 , 5, 6 , 7 , 8 , 9 , 10, "Jack" , "Queen", "King"}, {♦ , ♣, ♥ , ♠}}] DeckShuffle[deck_] := RandomSample[deck, Length@deck] DealFromDeck[] := (Print@First@deck; deck = deck[[2 ;; All]];)
Convert this C++ block to Mathematica, preserving its control flow and logic.
#include <iostream> #include <algorithm> #include <vector> #include <utility> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } int main() { using intpair = std::pair<int,int>; std::vector<intpair> pairs = { {21,15}, {17,23}, {36,...
CoprimeQ @@@ {{21, 15}, {17, 23}, {36, 12}, {18, 29}, {60, 15}}
Produce a functionally identical Mathematica code for the snippet given in C++.
#include <iostream> #include <algorithm> #include <vector> #include <utility> int gcd(int a, int b) { int c; while (b) { c = a; a = b; b = c % b; } return a; } int main() { using intpair = std::pair<int,int>; std::vector<intpair> pairs = { {21,15}, {17,23}, {36,...
CoprimeQ @@@ {{21, 15}, {17, 23}, {36, 12}, {18, 29}, {60, 15}}
Change the programming language of this snippet from C++ to Mathematica without modifying what it does.
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) contin...
ClearAll[PerfectTotientNumberQ] PerfectTotientNumberQ[n_Integer] := Total[Rest[Most[FixedPointList[EulerPhi, n]]]] == n res = {}; i = 0; While[Length[res] < 20, i++; If[PerfectTotientNumberQ[i], AppendTo[res, i]] ] res
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <cassert> #include <iostream> #include <vector> class totient_calculator { public: explicit totient_calculator(int max) : totient_(max + 1) { for (int i = 1; i <= max; ++i) totient_[i] = i; for (int i = 2; i <= max; ++i) { if (totient_[i] < i) contin...
ClearAll[PerfectTotientNumberQ] PerfectTotientNumberQ[n_Integer] := Total[Rest[Most[FixedPointList[EulerPhi, n]]]] == n res = {}; i = 0; While[Length[res] < 20, i++; If[PerfectTotientNumberQ[i], AppendTo[res, i]] ] res
Generate an equivalent Mathematica version of this C++ code.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_lah_numbers { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_lah_numbers::get(int n, int k) { if (k == ...
ClearAll[Lah] Lah[n_?Positive, 0] := 0 Lah[0, k_?Positive] := 0 Lah[n_, n_] := 1 Lah[n_, 1] := n! Lah[n_, k_] := (-1)^n (n! ((n - 1)!))/((k! ((k - 1)!)) ((n - k)!)) Table[Lah[i, j], {i, 0, 12}, {j, 0, 12}] // Grid Max[Lah[100, Range[0, 100]]]
Produce a language-to-language conversion: from C++ to Mathematica, same semantics.
#include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <gmpxx.h> using integer = mpz_class; class unsigned_lah_numbers { public: integer get(int n, int k); private: std::map<std::pair<int, int>, integer> cache_; }; integer unsigned_lah_numbers::get(int n, int k) { if (k == ...
ClearAll[Lah] Lah[n_?Positive, 0] := 0 Lah[0, k_?Positive] := 0 Lah[n_, n_] := 1 Lah[n_, 1] := n! Lah[n_, k_] := (-1)^n (n! ((n - 1)!))/((k! ((k - 1)!)) ((n - k)!)) Table[Lah[i, j], {i, 0, 12}, {j, 0, 12}] // Grid Max[Lah[100, Range[0, 100]]]
Convert this C++ snippet to Mathematica and keep its semantics consistent.
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); ...
twoSum[data_List, sum_] := Block[{indices = Subsets[Range@Length@data, {2}]}, Cases[indices, _?(Total@data[[#]] == sum &)]] twoSum[{0, 2, 11, 19, 90}, 21] // TableForm
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <iostream> #include <map> #include <tuple> #include <vector> using namespace std; pair<int, int> twoSum(vector<int> numbers, int sum) { auto m = map<int, int>(); for (size_t i = 0; i < numbers.size(); ++i) { auto key = sum - numbers[i]; if (m.find(key) != m.end()) { return make_pair(m[key], i); ...
twoSum[data_List, sum_] := Block[{indices = Subsets[Range@Length@data, {2}]}, Cases[indices, _?(Total@data[[#]] == sum &)]] twoSum[{0, 2, 11, 19, 90}, 21] // TableForm
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <algorithm> #include <cassert> #include <iostream> #include <iterator> #include <vector> template <typename iterator> void cocktail_shaker_sort(iterator begin, iterator end) { if (begin == end) return; for (--end; begin < end; ) { iterator new_begin = end; iterator new_end = b...
ClearAll[CocktailShakerSort] CocktailShakerSort[in_List] := Module[{x = in, swapped, begin = 1, end = Length[in] - 1}, swapped = True; While[swapped, swapped = False; Do[ If[x[[i]] > x[[i + 1]], x[[{i, i + 1}]] //= Reverse; swapped = True; ] , {i, begin, end} ]; end--; ...
Please provide an equivalent version of this C++ code in Mathematica.
#include <iostream> #include <cstdint> #include "prime_sieve.hpp" typedef uint32_t integer; int count_digits(integer n) { int digits = 0; for (; n > 0; ++digits) n /= 10; return digits; } integer change_digit(integer n, int index, int new_digit) { integer p = 1; integer changed = 0; ...
ClearAll[Unprimeable] Unprimeable[in_Integer] := Module[{id, new, pos}, id = IntegerDigits[in]; pos = Catenate@Table[ Table[ new = id; new[[d]] = n; new , {n, 0, 9} ] , {d, Length[id]} ]; pos //= Map[FromDigits]; NoneTrue[pos, PrimeQ] ] res = {}; PrintTe...
Ensure the translated Mathematica code behaves exactly like the original C++ snippet.
#include <iomanip> #include <iostream> unsigned int divisor_count(unsigned int n) { unsigned int total = 1; for (; (n & 1) == 0; n >>= 1) ++total; for (unsigned int p = 3; p * p <= n; p += 2) { unsigned int count = 1; for (; n % p == 0; n /= p) ++count; ...
Take[Select[Range[10000], Divisible[#, Length[Divisors[#]]] &], 100]
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2...
Select[Prime[Range@PrimePi[4999]], IntegerDigits /* Total /* EqualTo[25]]
Please provide an equivalent version of this C++ code in Mathematica.
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <string> #include <gmpxx.h> bool is_probably_prime(const mpz_class& n) { return mpz_probab_prime_p(n.get_mpz_t(), 3) != 0; } bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2...
Select[Prime[Range@PrimePi[4999]], IntegerDigits /* Total /* EqualTo[25]]
Maintain the same structure and functionality when rewriting this code in Mathematica.
#include <array> #include <iostream> #include <list> #include <map> #include <vector> int main() { auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "green", "blue"}; auto myArray = std::array<std::vector<std::string>, 2>{myNumber...
a = {"foo", \[Pi], {<| "deep" -> {# + 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \ {{"programming"}, {"language!"}}}}|>}}; b = a; a[[2]] -= 3; a[[3, 1, 1, 1]] = #^2 &; Print[a]; Print[b];
Generate an equivalent Mathematica version of this C++ code.
#include <array> #include <iostream> #include <list> #include <map> #include <vector> int main() { auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"}; auto myColors = std::vector<std::string>{"red", "green", "blue"}; auto myArray = std::array<std::vector<std::string>, 2>{myNumber...
a = {"foo", \[Pi], {<| "deep" -> {# + 1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \ {{"programming"}, {"language!"}}}}|>}}; b = a; a[[2]] -= 3; a[[3, 1, 1, 1]] = #^2 &; Print[a]; Print[b];
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <cstdint> #include <algorithm> #include <iostream> #include <sstream> #include <gmpxx.h> typedef mpz_class integer; bool is_prime(const integer& n, int reps = 50) { return mpz_probab_prime_p(n.get_mpz_t(), reps); } std::string to_string(const integer& n) { std::ostringstream out; out << n; r...
ClearAll[RepUnit, CircularPrimeQ] RepUnit[n_] := (10^n - 1)/9 CircularPrimeQ[n_Integer] := Module[{id = IntegerDigits[n], nums, t}, AllTrue[ Range[Length[id]] , Function[{z}, t = FromDigits[RotateLeft[id, z]]; If[t < n, False , PrimeQ[t] ] ] ] ] Select[Range[200000], Circ...
Keep all operations the same but rewrite the snippet in Mathematica.
#include <cstdint> #include <iomanip> #include <iostream> #include <primesieve.hpp> 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) r...
ClearAll[fn] fn[n_] := Prime[n] Prime[n + 1] - Prime[n] - Prime[n + 1] a = -1; i = 1; res = {}; While[a < 10^4, a = fn[i]; i++; If[a < 10^4, AppendTo[res, a]] ] res
Please provide an equivalent version of this C++ code in Mathematica.
#include <cstdint> #include <iomanip> #include <iostream> #include <primesieve.hpp> 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) r...
ClearAll[fn] fn[n_] := Prime[n] Prime[n + 1] - Prime[n] - Prime[n + 1] a = -1; i = 1; res = {}; While[a < 10^4, a = fn[i]; i++; If[a < 10^4, AppendTo[res, a]] ] res
Rewrite this program in Mathematica while keeping its functionality equivalent to the C++ version.
#include <algorithm> template<typename ForwardIterator> void permutation_sort(ForwardIterator begin, ForwardIterator end) { while (std::next_permutation(begin, end)) { } }
PermutationSort[x_List] := NestWhile[RandomSample, x, Not[OrderedQ[#]] &]
Produce a functionally identical Mathematica code for the snippet given in C++.
int meaning_of_life();
#!/usr/bin/env MathKernel -script MeaningOfLife[] = 42 ScriptName[] = Piecewise[ { {"Interpreted", Position[$CommandLine, "-script", 1] == {}} }, $CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]] ] Program = ScriptName[]; If[StringMatchQ[Program, ".*scriptedmain.*"], Print["Main: The meaning of ...
Rewrite the snippet below in Mathematica so it works the same as the original C++ code.
int meaning_of_life();
#!/usr/bin/env MathKernel -script MeaningOfLife[] = 42 ScriptName[] = Piecewise[ { {"Interpreted", Position[$CommandLine, "-script", 1] == {}} }, $CommandLine[[Position[$CommandLine, "-script", 1][[1,1]] + 1]] ] Program = ScriptName[]; If[StringMatchQ[Program, ".*scriptedmain.*"], Print["Main: The meaning of ...
Port the following code from C++ to Mathematica with equivalent syntax and logic.
#include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) ...
ClearAll[summ] summ[n_] := FixedPoint[IntegerDigits /* Total, n] Select[Range[501, 999], PrimeQ[#] \[And] PrimeQ[summ[#]] &]
Write the same algorithm in Mathematica as shown in this C++ implementation.
#include <iostream> bool is_prime(unsigned int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (unsigned int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) ...
ClearAll[summ] summ[n_] := FixedPoint[IntegerDigits /* Total, n] Select[Range[501, 999], PrimeQ[#] \[And] PrimeQ[summ[#]] &]
Change the following C++ code into Mathematica without altering its purpose.
#include <windows.h> #include <iostream> #include <string> using namespace std; class lastSunday { public: lastSunday() { m[0] = "JANUARY: "; m[1] = "FEBRUARY: "; m[2] = "MARCH: "; m[3] = "APRIL: "; m[4] = "MAY: "; m[5] = "JUNE: "; m[6] = "JULY: "; m[7] = "AUGUST: ";...
LastSundays[year_] := Table[Last@ DayRange[{year, i}, DatePlus[{year, i}, {{1, "Month"}, {-1, "Day"}}], Sunday], {i, 12}] LastSundays[2013]