Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into C++ but keep the logic exactly as in Python.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) ...
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t primes[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; for (au...
Ensure the translated C++ code behaves exactly like the original Python snippet.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) ...
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t primes[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; for (au...
Translate the given Python code snippet into C++ without altering its behavior.
from primesieve import primes import math def primepowers(k, upper_bound): ub = int(math.pow(upper_bound, 1/k) + .5) res = [(1,)] for p in primes(ub): a = [p**k] u = upper_bound // a[-1] while u >= p: a.append(a[-1]*p) u //= p res.append(tuple(a)) ...
#include <algorithm> #include <cmath> #include <cstdint> #include <iostream> #include <numeric> #include <vector> bool is_square_free(uint64_t n) { static constexpr uint64_t primes[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 }; for (au...
Keep all operations the same but rewrite the snippet in C++.
infile = open('infile.dat', 'rb') outfile = open('outfile.dat', 'wb') while True: onerecord = infile.read(80) if len(onerecord) < 80: break onerecordreversed = bytes(reversed(onerecord)) outfile.write(onerecordreversed) infile.close() outfile.close()
#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...
Rewrite the snippet below in C++ so it works the same as the original Python code.
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() for word in wordList: if len(word)>5 and word[:3].lower()==word[-3:].lower(): print(wo...
#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...
Transform the following Python implementation into C++, maintaining the same output and logic.
from math import sqrt def isGiuga(m): n = m f = 2 l = sqrt(n) while True: if n % f == 0: if ((m / f) - 1) % f != 0: return False n /= f if f > n: return True else: f += 1 if f > l: ...
#include <iostream> bool is_giuga(unsigned int n) { unsigned int m = n / 2; auto test_factor = [&m, n](unsigned int p) -> bool { if (m % p != 0) return true; m /= p; return m % p != 0 && (n / p - 1) % p == 0; }; if (!test_factor(3) || !test_factor(5)) return...
Convert this Python block to C++, preserving its control flow and logic.
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef...
#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...
Generate a C++ translation of this Python snippet without changing its computational steps.
from __future__ import print_function from __future__ import division def extended_synthetic_division(dividend, divisor): out = list(dividend) normalizer = divisor[0] for i in xrange(len(dividend)-(len(divisor)-1)): out[i] /= normalizer coef...
#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...
Write a version of this Python function in C++ with identical behavior.
import urllib.request urllib.request.urlretrieve("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt", "unixdict.txt") dictionary = open("unixdict.txt","r") wordList = dictionary.read().split('\n') dictionary.close() oddWordSet = set({}) for word in wordList: if len(word)>=9 and word[::2] in wordList: ...
#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 ...
Translate this program into C++ but keep the logic exactly as in Python.
from pprint import pprint as pp def to_indent(node, depth=0, flat=None): if flat is None: flat = [] if node: flat.append((depth, node[0])) for child in node[1]: to_indent(child, depth + 1, flat) return flat def to_nest(lst, depth=0, level=None): if level is None: le...
#include <iomanip> #include <iostream> #include <list> #include <string> #include <vector> #include <utility> #include <vector> class nest_tree; bool operator==(const nest_tree&, const nest_tree&); class nest_tree { public: explicit nest_tree(const std::string& name) : name_(name) {} nest_tree& add_child(con...
Rewrite the snippet below in C++ so it works the same as the original Python code.
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repd...
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
Preserve the algorithm and functionality while converting the code from Python to C++.
from collections import defaultdict rep = {'a' : {1 : 'A', 2 : 'B', 4 : 'C', 5 : 'D'}, 'b' : {1 : 'E'}, 'r' : {2 : 'F'}} def trstring(oldstring, repdict): seen, newchars = defaultdict(lambda:1, {}), [] for c in oldstring: i = seen[c] newchars.append(repdict[c][i] if c in repdict and i in repd...
#include <map> #include <iostream> #include <string> int main() { std::map<char, std::string> rep = {{'a', "DCaBA"}, {'b', "E"}, {'r', "Fr"}}; std::string magic = "abracadabra"; for(auto it = magic.begin(); it != magic.end(); ++it) { if(auto f = rep.find(*it); f != rep.end() && !f->second...
Generate a C++ translation of this Python snippet without changing its computational steps.
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { ...
Translate the given Python code snippet into C++ without altering its behavior.
from sympy import isprime for b in range(2, 17): print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])
#include <future> #include <iomanip> #include <iostream> #include <vector> #include <gmpxx.h> #include <primesieve.hpp> std::vector<uint64_t> repunit_primes(uint32_t base, const std::vector<uint64_t>& primes) { std::vector<uint64_t> result; for (uint64_t prime : primes) { ...
Transform the following Python implementation into C++, maintaining the same output and logic.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
#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;...
Write a version of this Python function in C++ with identical behavior.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
#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;...
Convert this Python block to C++, preserving its control flow and logic.
def is_Curzon(n, k): r = k * n return pow(k, n, r + 1) == r for k in [2, 4, 6, 8, 10]: n, curzons = 1, [] while len(curzons) < 1000: if is_Curzon(n, k): curzons.append(n) n += 1 print(f'Curzon numbers with k = {k}:') for i, c in enumerate(curzons[:50]): print...
#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;...
Translate the given Python code snippet into C++ without altering its behavior.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) ...
Generate a C++ translation of this Python snippet without changing its computational steps.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) ...
Port the provided Python code into C++ while preserving the original functionality.
from mpmath import mp heegner = [19,43,67,163] mp.dps = 50 x = mp.exp(mp.pi*mp.sqrt(163)) print("calculated Ramanujan's constant: {}".format(x)) print("Heegner numbers yielding 'almost' integers:") for i in heegner: print(" for {}: {} ~ {} error: {}".format(str(i),mp.exp(mp.pi*mp.sqrt(i)),round(mp.exp(mp.pi*mp.sqrt...
#include <iomanip> #include <iostream> #include <boost/math/constants/constants.hpp> #include <boost/multiprecision/cpp_dec_float.hpp> using big_float = boost::multiprecision::cpp_dec_float_100; big_float f(unsigned int n) { big_float pi(boost::math::constants::pi<big_float>()); return exp(sqrt(big_float(n)) ...
Maintain the same structure and functionality when rewriting this code in C++.
class Example(object): def foo(self): print("this is foo") def bar(self): print("this is bar") def __getattr__(self, name): def method(*args): print("tried to handle unknown method " + name) if args: print("it had arguments: " + str(args)) ...
class animal { public: virtual void bark() { throw "implement me: do not know how to bark"; } }; class elephant : public animal { }; int main() { elephant e; e.bark(); }
Convert the following code from Python to C++, ensuring the logic remains intact.
from itertools import (chain) def stringParse(lexicon): return lambda s: Node(s)( tokenTrees(lexicon)(s) ) def tokenTrees(wds): def go(s): return [Node(s)([])] if s in wds else ( concatMap(nxt(s))(wds) ) def nxt(s): return lambda w: parse( ...
#include <algorithm> #include <iostream> #include <optional> #include <set> #include <string> #include <string_view> #include <vector> struct string_comparator { using is_transparent = void; bool operator()(const std::string& lhs, const std::string& rhs) const { return lhs < rhs; } bool operato...
Preserve the algorithm and functionality while converting the code from Python to C++.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
Change the following Python code into C++ without altering its purpose.
from primesieve.numpy import primes from math import isqrt import numpy as np max_order = 9 blocks = [primes(10**n, 10**(n + 1)) for n in range(max_order)] def smallest_brilliant(lb): pos = 1 root = isqrt(lb) for blk in blocks: n = len(blk) if blk[-1]*blk[-1] < lb: pos += n*(n...
#include <algorithm> #include <chrono> #include <iomanip> #include <iostream> #include <locale> #include <vector> #include <primesieve.hpp> auto get_primes_by_digits(uint64_t limit) { primesieve::iterator pi; std::vector<std::vector<uint64_t>> primes_by_digits; std::vector<uint64_t> primes; for (uint6...
Convert this Python snippet to C++ and keep its semantics consistent.
import os,sys,zlib,urllib.request def h ( str,x=9 ): for c in str : x = ( x*33 + ord( c )) & 0xffffffffff return x def cache ( func,*param ): n = 'cache_%x.bin'%abs( h( repr( param ))) try : return eval( zlib.decompress( open( n,'rb' ).read())) except : pass s = func( *param ) ...
#include <algorithm> #include <fstream> #include <iostream> #include <map> #include <string> #include <vector> using word_map = std::map<size_t, std::vector<std::string>>; bool one_away(const std::string& s1, const std::string& s2) { if (s1.size() != s2.size()) return false; bool result = false; ...
Port the following code from Python to C++ with equivalent syntax and logic.
import sys import pygame pygame.init() clk = pygame.time.Clock() if pygame.joystick.get_count() == 0: raise IOError("No joystick detected") joy = pygame.joystick.Joystick(0) joy.init() size = width, height = 600, 600 screen = pygame.display.set_mode(size) pygame.display.set_caption("Joystick Tester") frame...
#include <stdio.h> #include <stdlib.h> void clear() { for(int n = 0;n < 10; n++) { printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n"); } } #define UP "00^00\r\n00|00\r\n00000\r\n" #define DOWN "00000\r\n00|00\r\n00v00\r\n" #define LEFT "00000\r\n<--00\r\n00000\r\n" #define RIGHT "00000\r\n00-->\r\n00000\r\...
Convert this Python block to C++, preserving its control flow and logic.
from primesieve import primes LIMIT = 10**9 pri = primes(LIMIT * 5) gapstarts = {} for i in range(1, len(pri)): if pri[i] - pri[i - 1] not in gapstarts: gapstarts[pri[i] - pri[i - 1]] = pri[i - 1] PM, GAP1, = 10, 2 while True: while GAP1 not in gapstarts: GAP1 += 2 start1 = gapstarts[GAP...
#include <iostream> #include <locale> #include <unordered_map> #include <primesieve.hpp> class prime_gaps { public: prime_gaps() { last_prime_ = iterator_.next_prime(); } uint64_t find_gap_start(uint64_t gap); private: primesieve::iterator iterator_; uint64_t last_prime_; std::unordered_map<uint64...
Produce a language-to-language conversion: from Python to C++, same semantics.
def dList(n, start): start -= 1 a = range(n) a[start] = a[0] a[0] = start a[1:] = sorted(a[1:]) first = a[1] r = [] def recurse(last): if (last == first): for j,v in enumerate(a[1:]): if j + 1 == v: ...
#include <algorithm> #include <functional> #include <iostream> #include <numeric> #include <vector> typedef std::vector<std::vector<int>> matrix; matrix dList(int n, int start) { start--; std::vector<int> a(n); std::iota(a.begin(), a.end(), 0); a[start] = a[0]; a[0] = start; std::sort(a.begi...
Write the same algorithm in C++ as shown in this Python implementation.
from sympy import primerange PRIMES1M = list(primerange(1, 1_000_000)) ASBASE10SORT = [str(sorted(list(str(i)))) for i in PRIMES1M] ORMISTONS = [(PRIMES1M[i - 1], PRIMES1M[i]) for i in range(1, len(PRIMES1M)) if ASBASE10SORT[i - 1] == ASBASE10SORT[i]] print('First 30 Ormiston pairs:') for (i, o) in en...
#include <array> #include <iomanip> #include <iostream> #include <utility> #include <primesieve.hpp> class ormiston_pair_generator { public: ormiston_pair_generator() { prime_ = pi_.next_prime(); } std::pair<uint64_t, uint64_t> next_pair() { for (;;) { uint64_t prime = prime_; ...
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
import itertools import re RE_BARCODE = re.compile( r"^(?P<s_quiet> +)" r"(?P<s_guard> r"(?P<left>[ r"(?P<m_guard> r"(?P<right>[ r"(?P<e_guard> r"(?P<e_quiet> +)$" ) LEFT_DIGITS = { (0, 0, 0, 1, 1, 0, 1): 0, (0, 0, 1, 1, 0, 0, 1): 1, (0, 0, 1, 0, 0, 1, 1): 2, (0, 1,...
#include <iostream> #include <locale> #include <map> #include <vector> std::string trim(const std::string &str) { auto s = str; auto it1 = std::find_if(s.rbegin(), s.rend(), [](char ch) { return !std::isspace<char>(ch, std::locale::classic()); }); s.erase(it1.base(), s.end()); auto it2 = st...
Write the same code in C++ as shown below in Python.
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if ...
#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; ...
Translate the given Python code snippet into C++ without altering its behavior.
from string import ascii_uppercase from itertools import product from re import findall def uniq(seq): seen = {} return [seen.setdefault(x, x) for x in seq if x not in seen] def partition(seq, n): return [seq[i : i + n] for i in xrange(0, len(seq), n)] def playfair(key, from_ = 'J', to = None): if ...
#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; ...
Maintain the same structure and functionality when rewriting this code in C++.
from fractions import Fraction def harmonic_series(): n, h = Fraction(1), Fraction(1) while True: yield h h += 1 / (n + 1) n += 1 if __name__ == '__main__': from itertools import islice for n, d in (h.as_integer_ratio() for h in islice(harmonic_series(), 20)): print(n,...
#include <iomanip> #include <iostream> #include <boost/rational.hpp> #include <boost/multiprecision/gmp.hpp> using integer = boost::multiprecision::mpz_int; using rational = boost::rational<integer>; class harmonic_generator { public: rational next() { rational result = term_; term_ += rational(1,...
Write a version of this Python function in C++ with identical behavior.
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) ...
#include <iostream> #include <fstream> #include <queue> #include <string> #include <algorithm> #include <cstdio> int main(int argc, char* argv[]); void write_vals(int* const, const size_t, const size_t); std::string mergeFiles(size_t); struct Compare { bool operator() ( std::pair<int, int>& p1, std::...
Convert the following code from Python to C++, ensuring the logic remains intact.
import io def sort_large_file(n: int, source: open, sink: open, file_opener = open)->None: mergers = [] while True: text = list(source.read(n)) if not len(text): break; text.sort() merge_me = file_opener() merge_me.write(''.join(text)) ...
#include <iostream> #include <fstream> #include <queue> #include <string> #include <algorithm> #include <cstdio> int main(int argc, char* argv[]); void write_vals(int* const, const size_t, const size_t); std::string mergeFiles(size_t); struct Compare { bool operator() ( std::pair<int, int>& p1, std::...
Convert the following code from Python to C++, ensuring the logic remains intact.
class NG: def __init__(self, a1, a, b1, b): self.a1, self.a, self.b1, self.b = a1, a, b1, b def ingress(self, n): self.a, self.a1 = self.a1, self.a + self.a1 * n self.b, self.b1 = self.b1, self.b + self.b1 * n @property def needterm(self): return (self.b == 0 or self.b1 == 0) or not self.a//se...
class matrixNG { private: virtual void consumeTerm(){} virtual void consumeTerm(int n){} virtual const bool needTerm(){} protected: int cfn = 0, thisTerm; bool haveTerm = false; friend class NG; }; class NG_4 : public matrixNG { private: int a1, a, b1, b, t; const bool needTerm() { if...
Preserve the algorithm and functionality while converting the code from Python to C++.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, ...
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
Convert the following code from Python to C++, ensuring the logic remains intact.
from fractions import Fraction from math import floor from itertools import islice, groupby def cw(): a = Fraction(1) while True: yield a a = 1 / (2 * floor(a) + 1 - a) def r2cf(rational): num, den = rational.numerator, rational.denominator while den: num, (digit, den) = den, ...
#include <iostream> #include <vector> #include <boost/rational.hpp> using rational = boost::rational<unsigned long>; unsigned long floor(const rational& r) { return r.numerator()/r.denominator(); } rational calkin_wilf_next(const rational& term) { return 1UL/(2UL * floor(term) + 1UL - term); } std::vector<u...
Change the following Python code into C++ without altering its purpose.
def facpropzeros(N, verbose = True): proportions = [0.0] * N fac, psum = 1, 0.0 for i in range(N): fac *= i + 1 d = list(str(fac)) psum += sum(map(lambda x: x == '0', d)) / len(d) proportions[i] = psum / (i + 1) if verbose: print("The mean proportion of 0 in fact...
#include <array> #include <chrono> #include <iomanip> #include <iostream> #include <vector> auto init_zc() { std::array<int, 1000> zc; zc.fill(0); zc[0] = 3; for (int x = 1; x <= 9; ++x) { zc[x] = 2; zc[10 * x] = 2; zc[100 * x] = 2; for (int y = 10; y <= 90; y += 10) { ...
Convert the following code from Python to C++, ensuring the logic remains intact.
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for ...
#include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator> typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t; double distance_between(const point_t& a, const point_t& b) { return std::s...
Rewrite the snippet below in C++ so it works the same as the original Python code.
from random import randint, randrange from operator import itemgetter, attrgetter infinity = float('inf') def bruteForceClosestPair(point): numPoints = len(point) if numPoints < 2: return infinity, (None, None) return min( ((abs(point[i] - point[j]), (point[i], point[j])) for ...
#include <iostream> #include <vector> #include <utility> #include <cmath> #include <random> #include <chrono> #include <algorithm> #include <iterator> typedef std::pair<double, double> point_t; typedef std::pair<point_t, point_t> points_t; double distance_between(const point_t& a, const point_t& b) { return std::s...
Transform the following Python implementation into C++, maintaining the same output and logic.
var num = 12 var pointer = ptr(num) print pointer @unsafe pointer.addr = 0xFFFE
int i; void* address_of_i = &i;
Please provide an equivalent version of this Python code in C++.
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass class Lab(Dog): pass class Collie(Dog): pass
class Animal { }; class Dog: public Animal { }; class Lab: public Dog { }; class Collie: public Dog { }; class Cat: public Animal { };
Transform the following Python implementation into C++, maintaining the same output and logic.
hash = dict() hash = dict(red="FF0000", green="00FF00", blue="0000FF") hash = { 'key1':1, 'key2':2, } value = hash[key]
#include <map>
Rewrite the snippet below in C++ so it works the same as the original Python code.
size(300, 300) background(0) radius = min(width, height) / 2.0 cx, cy = width / 2, width / 2 for x in range(width): for y in range(height): rx = x - cx ry = y - cy s = sqrt(rx ** 2 + ry ** 2) / radius if s <= 1.0: h = ((atan2(ry, rx) / PI) + 1.0) /...
#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 <=...
Rewrite the snippet below in C++ so it works the same as the original Python code.
pal = [0] * 128 r = 42 g = 84 b = 126 rd = gd = bd = False def setup(): global buffer size(600, 600) frameRate(25) buffer = [None] * width * height for x in range(width): for y in range(width): value = int(((128 + (128 * sin(x / 32.0))) + (128 + (128 *...
#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 ); } ...
Generate an equivalent C++ version of this Python code.
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumera...
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostrea...
Ensure the translated C++ code behaves exactly like the original Python snippet.
from itertools import product from collections import defaultdict class Sandpile(): def __init__(self, gridtext): array = [int(x) for x in gridtext.strip().split()] self.grid = defaultdict(int, {(i //3, i % 3): x for i, x in enumera...
#include <algorithm> #include <array> #include <cassert> #include <initializer_list> #include <iostream> constexpr size_t sp_rows = 3; constexpr size_t sp_columns = 3; constexpr size_t sp_cells = sp_rows * sp_columns; constexpr int sp_limit = 4; class abelian_sandpile { friend std::ostream& operator<<(std::ostrea...
Generate an equivalent C++ version of this Python code.
print "Goodbye, World!"
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
Produce a language-to-language conversion: from Python to C++, same semantics.
print "Goodbye, World!"
#include <iostream> int main() { using namespace std; cout << "Hello, World!" << endl; return 0; }
Translate the given Python code snippet into C++ without altering its behavior.
class Point(object): def __init__(self, x=0.0, y=0.0): self.x = x self.y = y def __repr__(self): return '<Point 0x%x x: %f y: %f>' % (id(self), self.x, self.y) class Circle(object): def __init__(self, center=None, radius=1.0): self.center = center or Point() self.rad...
#include <cstdio> #include <cstdlib> class Point { protected: int x, y; public: Point(int x0 = 0, int y0 = 0) : x(x0), y(y0) {} Point(const Point &p) : x(p.x), y(p.y) {} virtual ~Point() {} const Point& operator=(const Point &p) { if (this != &p) { x = p.x; y = p.y;...
Port the following code from Python to C++ with equivalent syntax and logic.
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if ...
#include <gmpxx.h> #include <primesieve.hpp> #include <iostream> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += "...
Produce a functionally identical C++ code for the snippet given in Python.
from sympy import isprime def wagstaff(N): pri, wcount = 1, 0 while wcount < N: pri += 2 if isprime(pri): wag = (2**pri + 1) // 3 if isprime(wag): wcount += 1 print(f'{wcount: 3}: {pri: 5} => ', f'{wag:,}' if ...
#include <gmpxx.h> #include <primesieve.hpp> #include <iostream> using big_int = mpz_class; std::string to_string(const big_int& num, size_t n) { std::string str = num.get_str(); size_t len = str.size(); if (len > n) { str = str.substr(0, n / 2) + "..." + str.substr(len - n / 2); str += "...
Convert this Python block to C++, preserving its control flow and logic.
from collections import UserDict import copy class Dict(UserDict): def __init__(self, dict=None, **kwargs): self.__init = True super().__init__(dict, **kwargs) self.default = copy.deepcopy(self.data) self.__init = False def __delitem__(self, key): if key in sel...
#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;...
Ensure the translated C++ code behaves exactly like the original Python snippet.
from itertools import groupby def magic_numbers(base): hist = [] n = l = i = 0 while True: l += 1 hist.extend((n + digit, l) for digit in range(-n % l, base, l)) i += 1 if i == len(hist): return hist n, l = hist[i] n *= base mn = magic_numbers(10...
#include <array> #include <iostream> #include <numeric> #include <vector> #include <boost/multiprecision/cpp_int.hpp> using boost::multiprecision::uint128_t; class magic_number_generator { public: magic_number_generator() : magic_(10) { std::iota(magic_.begin(), magic_.end(), 0); } bool next(uint...
Generate a C++ translation of this Python snippet without changing its computational steps.
from collections import deque from typing import Iterable from typing import Iterator from typing import Reversible days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] colors = deque( [ "red", "yellow", "pink", "gr...
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto...
Translate the given Python code snippet into C++ without altering its behavior.
from collections import deque from typing import Iterable from typing import Iterator from typing import Reversible days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ] colors = deque( [ "red", "yellow", "pink", "gr...
#include <iostream> #include <list> #include <string> #include <vector> using namespace std; void PrintContainer(forward_iterator auto start, forward_iterator auto sentinel) { for(auto it = start; it != sentinel; ++it) { cout << *it << " "; } cout << "\n"; } void FirstFourthFifth(input_iterator auto...
Convert this Python block to C++, preserving its control flow and logic.
from math import floor, sqrt from datetime import datetime def main(): start = datetime.now() for i in xrange(1, 10 ** 11): if rare(i): print "found a rare:", i end = datetime.now() print "time elapsed:", end - start def is_square(n): s = floor(sqrt(n + 0.5)) return s * s == n def reverse(n): return ...
#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...
Change the programming language of this snippet from Python to C++ without modifying what it does.
print('\n'.join((f'{x[0]}: {" ".join(sorted(x[1]))}' if len(x[1]) < 30 else f'{x[0]}: {len(x[1])} words' for x in (x for x in ((n, [x[1] for x in l if x[0] == n]) for n in range(maxlen, -1, -1)) if x[1]))) if (maxlen := max(l := [(len(c), w) for w in [l for l in [l.rstrip() for l in open('unixdict.txt')] if...
#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...
Write the same algorithm in C++ as shown in this Python implementation.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
Translate the given Python code snippet into C++ without altering its behavior.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
Translate the given Python code snippet into C++ without altering its behavior.
for i in range(65,123): check = 1 for j in range(2,i): if i%j == 0: check = 0 if check==1: print(chr(i),end='')
#include <algorithm> #include <cstdlib> #include <fstream> #include <iomanip> #include <iostream> #include <string> #include "prime_sieve.hpp" int main(int argc, char** argv) { const char* filename(argc < 2 ? "unixdict.txt" : argv[1]); std::ifstream in(filename); if (!in) { std::cerr << "Cannot ope...
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
def Riordan(N): a = [1, 0, 1] for n in range(3, N): a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1)) return a rios = Riordan(10_000) for i in range(32): print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '') print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.') ...
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; ...
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
def Riordan(N): a = [1, 0, 1] for n in range(3, N): a.append((n - 1) * (2 * a[n - 1] + 3 * a[n - 2]) // (n + 1)) return a rios = Riordan(10_000) for i in range(32): print(f'{rios[i] : 18,}', end='\n' if (i + 1) % 4 == 0 else '') print(f'The 1,000th Riordan has {len(str(rios[999]))} digits.') ...
#include <iomanip> #include <iostream> #include <gmpxx.h> using big_int = mpz_class; class riordan_number_generator { public: big_int next(); private: big_int a0_ = 1; big_int a1_ = 0; int n_ = 0; }; big_int riordan_number_generator::next() { int n = n_++; if (n == 0) return a0_; ...
Convert the following code from Python to C++, ensuring the logic remains intact.
from functools import reduce from sympy import divisors FOUND = 0 for num in range(1, 1_000_000): divprod = reduce(lambda x, y: x * y, divisors(num)[:-1])if num > 1 else 1 if num * num * num == divprod: FOUND += 1 if FOUND <= 50: print(f'{num:5}', end='\n' if FOUND % 10 == 0 else...
#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; total *= ...
Ensure the translated C++ code behaves exactly like the original Python snippet.
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(sel...
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
Convert the following code from Python to C++, ensuring the logic remains intact.
import operator class AstNode(object): def __init__( self, opr, left, right ): self.opr = opr self.l = left self.r = right def eval(self): return self.opr(self.l.eval(), self.r.eval()) class LeafNode(object): def __init__( self, valStrg ): self.v = int(valStrg) def eval(sel...
#include <boost/spirit.hpp> #include <boost/spirit/tree/ast.hpp> #include <string> #include <cassert> #include <iostream> #include <istream> #include <ostream> using boost::spirit::rule; using boost::spirit::parser_tag; using boost::spirit::ch_p; using boost::spirit::real_p; using boost::spirit::tree_no...
Can you help me rewrite this code in C++ instead of Python, keeping it the same logically?
import textwrap from itertools import pairwise from typing import Iterator from typing import List import primesieve def primes() -> Iterator[int]: it = primesieve.Iterator() while True: yield it.next_prime() def triplewise(iterable): for (a, _), (b, c) in pairwise(pairwise(iterable)): ...
#include <array> #include <iostream> #include <primesieve.hpp> class ormiston_triple_generator { public: ormiston_triple_generator() { for (int i = 0; i < 2; ++i) { primes_[i] = pi_.next_prime(); digits_[i] = get_digits(primes_[i]); } } std::array<uint64_t, 3> next_...
Produce a language-to-language conversion: from Python to C++, same semantics.
from sympy import isprime, divisors def is_super_Poulet(n): return not isprime(n) and 2**(n - 1) % n == 1 and all((2**d - 2) % d == 0 for d in divisors(n)) spoulets = [n for n in range(1, 1_100_000) if is_super_Poulet(n)] print('The first 20 super-Poulet numbers are:', spoulets[:20]) idx1m, val1m = next((i, v)...
#include <algorithm> #include <iostream> #include <vector> std::vector<unsigned int> divisors(unsigned int n) { std::vector<unsigned int> result{1}; unsigned int power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) result.push_back(power); for (unsigned int p = 3; p * p <= n; p += 2) { ...
Convert the following code from Python to C++, ensuring the logic remains intact.
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
#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...
Write the same code in C++ as shown below in Python.
gridsize = (6, 4) minerange = (0.2, 0.6) try: raw_input except: raw_input = input import random from itertools import product from pprint import pprint as pp def gridandmines(gridsize=gridsize, minerange=minerange): xgrid, ygrid = gridsize minmines, maxmines = minerange minecount = xgri...
#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...
Write the same algorithm in C++ as shown in this Python implementation.
def _notcell(c): return '0' if c == '1' else '1' def eca_infinite(cells, rule): lencells = len(cells) rulebits = '{0:08b}'.format(rule) neighbours2next = {'{0:03b}'.format(n):rulebits[::-1][n] for n in range(8)} c = cells while True: yield c c = _notcell(c[0])*2 + c + _notcell(c...
#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...
Change the following Python code into C++ without altering its purpose.
import sys def fatal_error(errtext): print("%" + errtext) print("usage: " + sys.argv[0] + " [filename.cp]") sys.exit(1) fname = None source = None try: fname = sys.argv[1] source = open(fname).read() except: fatal_error("error while trying to read from specified file") lines = source.split("\n") clipboard...
#include <fstream> #include <iostream> #include <sstream> #include <streambuf> #include <string> #include <stdlib.h> using namespace std; void fatal_error(string errtext, char *argv[]) { cout << "%" << errtext << endl; cout << "usage: " << argv[0] << " [filename.cp]" << endl; exit(1); } string& ltrim(string& ...
Port the provided Python code into C++ while preserving the original functionality.
from sympy import sieve def nonpairsums(include1=False, limit=20_000): tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve) for i in range(limit+2)] if include1: tpri[1] = True twinsums = [False] * (limit * 2) for i in range(limit): for j in range(limit-i+1): ...
#include <iomanip> #include <iostream> #include <vector> std::vector<bool> prime_sieve(int limit) { std::vector<bool> sieve(limit, true); if (limit > 0) sieve[0] = false; if (limit > 1) sieve[1] = false; for (int i = 4; i < limit; i += 2) sieve[i] = false; for (int p = 3, sq...
Transform the following Python implementation into C++, maintaining the same output and logic.
def kosaraju(g): class nonlocal: pass size = len(g) vis = [False]*size l = [0]*size nonlocal.x = size t = [[]]*size def visit(u): if not vis[u]: vis[u] = True for v in g[u]: visit(v) t[v] = t[v] + [u] non...
#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...
Change the programming language of this snippet from Python to C++ without modifying what it does.
example1 = 3 example2 = 3.0 example3 = True example4 = "hello" example1 = "goodbye"
int a;
Port the following code from Python to C++ with equivalent syntax and logic.
from numpy import ndarray from math import isqrt def pritchard(limit): members = ndarray(limit + 1, dtype=bool) members.fill(False) members[1] = True steplength, prime, rtlim, nlimit = 1, 2, isqrt(limit), 2 primes = [] while prime <= rtlim: if steplength < limit: for...
#include <cstring> #include <string> #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <ctime> void Extend (uint32_t w[], uint32_t &w_end, uint32_t &length, uint32_t n, bool d[], uint32_t &w_end_max) { uint32_t i, j, x; i = 0; j = w_end; x = length + 1; while (x <= n) { ...
Rewrite the snippet below in C++ so it works the same as the original Python code.
from __future__ import annotations import functools import math import os from typing import Any from typing import Callable from typing import Generic from typing import List from typing import TypeVar from typing import Union T = TypeVar("T") class Writer(Generic[T]): def __init__(self, value: Union[T, Wri...
#include <cmath> #include <iostream> #include <string> using namespace std; struct LoggingMonad { double Value; string Log; }; auto operator>>(const LoggingMonad& monad, auto f) { auto result = f(monad.Value); return LoggingMonad{result.Value, monad.Log + "\n" + result.Log}; } auto Root = [](doub...
Convert the following code from Python to C++, ensuring the logic remains intact.
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x...
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) co...
Rewrite this program in C++ while keeping its functionality equivalent to the Python version.
from pprint import pprint as pp class Template(): def __init__(self, structure): self.structure = structure self.used_payloads, self.missed_payloads = [], [] def inject_payload(self, id2data): def _inject_payload(substruct, i2d, used, missed): used.extend(i2d[x...
#include <iostream> #include <set> #include <tuple> #include <vector> using namespace std; template<typename P> void PrintPayloads(const P &payloads, int index, bool isLast) { if(index < 0 || index >= (int)size(payloads)) cout << "null"; else cout << "'" << payloads[index] << "'"; if (!isLast) co...
Maintain the same structure and functionality when rewriting this code in C++.
from pyprimesieve import primes def digitsum(num): return sum(int(c) for c in str(num)) def generate_honaker(limit=5_000_000): honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)] for hcount, (ppi, pri) in enumerate(honaker): yield hcount + 1...
#include <iomanip> #include <iostream> #include <sstream> #include <utility> #include <primesieve.hpp> uint64_t digit_sum(uint64_t n) { uint64_t sum = 0; for (; n > 0; n /= 10) sum += n % 10; return sum; } class honaker_prime_generator { public: std::pair<uint64_t, uint64_t> next(); private:...
Convert this Python snippet to C++ and keep its semantics consistent.
from sympy import isprime from math import log from numpy import ndarray max_value = 1_000_000 all_primes = [i for i in range(max_value + 1) if isprime(i)] powers_of_2 = [2**i for i in range(int(log(max_value, 2)))] allvalues = ndarray(max_value, dtype=bool) allvalues[:] = True for i in all_primes: for j in p...
#include <iomanip> #include <iostream> bool is_prime(int n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; for (int p = 5; p * p <= n; p += 4) { if (n % p == 0) return false; p += 2; if (n % p == 0) ...
Translate this program into C++ but keep the logic exactly as in Python.
import random def encode(correct, guess): output_arr = [''] * len(correct) for i, (correct_char, guess_char) in enumerate(zip(correct, guess)): output_arr[i] = 'X' if guess_char == correct_char else 'O' if guess_char in correct else '-' return ''.join(output_arr) def safe_int_input(prompt, min...
#include <iostream> #include <algorithm> #include <ctime> #include <string> #include <vector> typedef std::vector<char> vecChar; class master { public: master( size_t code_len, size_t clr_count, size_t guess_count, bool rpt ) { std::string color = "ABCDEFGHIJKLMNOPQRST"; if( code_len < 4 ) code_l...
Ensure the translated C++ code behaves exactly like the original Python snippet.
from math import gcd from sympy import divisors def zsig(num, aint, bint): assert aint > bint dexpms = [aint**i - bint**i for i in range(1, num)] dexpn = aint**num - bint**num return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)]) tests = [(2, 1), (3, 1), (4, 1), (5, ...
#include <algorithm> #include <cstdint> #include <iostream> #include <numeric> #include <vector> std::vector<uint64_t> divisors(uint64_t n) { std::vector<uint64_t> result{1}; uint64_t power = 2; for (; (n & 1) == 0; power <<= 1, n >>= 1) result.push_back(power); for (uint64_t p = 3; p * p <= n;...
Write the same algorithm in C++ as shown in this Python implementation.
from multiset import Multiset def tokenizetext(txt): arr = [] for wrd in txt.lower().split(' '): arr += ([wrd] if len(wrd) == 1 else [wrd[i:i+2] for i in range(len(wrd)-1)]) return Multiset(arr) def sorenson_dice(text1, text2): bc1, bc2 = tokenizetext(text1), toke...
#include <algorithm> #include <cctype> #include <cstdlib> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <sstream> #include <string> #include <vector> using bigram = std::pair<char, char>; std::multiset<bigram> bigrams(const std::string& phrase) { std::multiset<bigram> result; ...
Please provide an equivalent version of this C# code in C.
public class AverageLoopLength { private static int N = 100000; private static double analytical(int n) { double[] factorial = new double[n + 1]; double[] powers = new double[n + 1]; powers[0] = 1.0; factorial[0] = 1.0; for (int i = 1; i <= n; i++) { factorial[i] = factorial[i - 1] * i; powers[i] = ...
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define MAX_N 20 #define TIMES 1000000 double factorial(int n) { double f = 1; int i; for (i = 1; i <= n; i++) f *= i; return f; } double expected(int n) { double sum = 0; int i; for (i = 1; i <= n; i++) sum += factorial(n) / pow(n, ...
Please provide an equivalent version of this C# code in C.
class Program { static void Main() { string extra = "little"; string formatted = $"Mary had a {extra} lamb."; System.Console.WriteLine(formatted); } }
#include <stdio.h> int main() { const char *extra = "little"; printf("Mary had a %s lamb.\n", extra); return 0; }
Write the same algorithm in C as shown in this C# implementation.
using System; class Program { const long Lm = (long)1e18; const string Fm = "D18"; struct LI { public long lo, ml, mh, hi, tp; } static void inc(ref LI d, LI s) { if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; } if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; } if ((d....
#include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <gmp.h> mpz_t* partition(uint64_t n) { mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t)); mpz_init_set_ui(pn[0], 1); mpz_init_set_ui(pn[1], 1); for (uint64_t i = 2; i < n + 2; i ++) { mpz_init(pn[i]); for (uint64_t k = 1, ...
Produce a functionally identical C code for the snippet given in C#.
#include <cstdio> #include <vector> #include <bits/stdc++.h> using namespace std; int main() { vector<tuple<int, int>> w; int lst[4] = { 2, 3, 5, 7 }, sum; for (int x : lst) w.push_back({x, x}); while (w.size() > 0) { auto i = w[0]; w.erase(w.begin()); for (int x : lst) if ((sum = get<1>(i) + x) == 13) ...
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
Write the same algorithm in C as shown in this C# implementation.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm...
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
Translate this program into C but keep the logic exactly as in C#.
using System; using static System.Console; using LI = System.Collections.Generic.SortedSet<int>; class Program { static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) { if (lft == 0) res.Add(vlu); else if (lft > 0) foreach (int itm in set) res = unl(res, set, lft - itm, mul * 10, vlu + itm...
#include <stdbool.h> #include <stdio.h> bool primeDigitsSum13(int n) { int sum = 0; while (n > 0) { int r = n % 10; switch (r) { case 2: case 3: case 5: case 7: break; default: return false; } n /= 10; sum +...
Write the same algorithm in C as shown in this C# implementation.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); ...
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); ...
Convert this C# snippet to C and keep its semantics consistent.
using System; using System.IO; using System.Text; namespace RosettaCode { internal class Program { private const string FileName = "NOTES.TXT"; private static void Main(string[] args) { if (args.Length==0) { string txt = File.ReadAllText(FileName); Console.WriteLine(txt); ...
#include <stdio.h> #include <time.h> #define note_file "NOTES.TXT" int main(int argc, char**argv) { FILE *note = 0; time_t tm; int i; char *p; if (argc < 2) { if ((note = fopen(note_file, "r"))) while ((i = fgetc(note)) != EOF) putchar(i); } else if ((note = fopen(note_file, "a"))) { tm = time(0); ...
Change the programming language of this snippet from C# to C without modifying what it does.
using System; public static class Angles { public static void Main() => Print(-2, -1, 0, 1, 2, 6.2831853, 16, 57.2957795, 359, 6399, 1_000_000); public static void Print(params double[] angles) { string[] names = { "Degrees", "Gradians", "Mils", "Radians" }; Func<double, double> rnd = a => Mat...
#define PI 3.141592653589793 #define TWO_PI 6.283185307179586 double normalize2deg(double a) { while (a < 0) a += 360; while (a >= 360) a -= 360; return a; } double normalize2grad(double a) { while (a < 0) a += 400; while (a >= 400) a -= 400; return a; } double normalize2mil(double a) { while (a < 0) a +...
Transform the following C# implementation into C, maintaining the same output and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaCodeTasks { class Program { static void Main ( string[ ] args ) { FindCommonDirectoryPath.Test ( ); } } class FindCommonDirectoryPath { public static void Test ( ) { Console.WriteLine ( "Find ...
#include <stdio.h> int common_len(const char *const *names, int n, char sep) { int i, pos; for (pos = 0; ; pos++) { for (i = 0; i < n; i++) { if (names[i][pos] != '\0' && names[i][pos] == names[0][pos]) continue; while (pos > 0 && names[0][--pos] != sep); return pos; } } return 0; } in...
Translate this program into C but keep the logic exactly as in C#.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; ...
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ...
Please provide an equivalent version of this C# code in C.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; ...
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ...
Port the provided C# code into C while preserving the original functionality.
using System; using System.Collections.Generic; namespace RecamanSequence { class Program { static void Main(string[] args) { List<int> a = new List<int>() { 0 }; HashSet<int> used = new HashSet<int>() { 0 }; HashSet<int> used1000 = new HashSet<int>() { 0 }; ...
#include <stdio.h> #include <stdlib.h> #include <gmodule.h> typedef int bool; int main() { int i, n, k = 0, next, *a; bool foundDup = FALSE; gboolean alreadyUsed; GHashTable* used = g_hash_table_new(g_direct_hash, g_direct_equal); GHashTable* used1000 = g_hash_table_new(g_direct_hash, g_direct_equ...
Generate an equivalent C version of this C# code.
using System; using System.Runtime.InteropServices; public unsafe class Program { public static unsafe void HeapMemory() { const int HEAP_ZERO_MEMORY = 0x00000008; const int size = 1000; int ph = GetProcessHeap(); void* pointer = HeapAlloc(ph, HEAP_ZERO_MEMORY, size); if...
#include <stdlib.h> #define SIZEOF_MEMB (sizeof(int)) #define NMEMB 100 int main() { int *ints = malloc(SIZEOF_MEMB*NMEMB); ints = realloc(ints, sizeof(int)*(NMEMB+1)); int *int2 = calloc(NMEMB, SIZEOF_MEMB); free(ints); free(int2); return 0; }
Port the following code from C# to C with equivalent syntax and logic.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RosettaTicTacToe { class Program { static string[][] Players = new string[][] { new string[] { "COMPUTER", "X" }, new string[] { "HUMAN", "O" } }; const int Unplayed = -1; const...
#include <stdio.h> #include <stdlib.h> int b[3][3]; int check_winner() { int i; for (i = 0; i < 3; i++) { if (b[i][0] && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]; if (b[0][i] && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]; } if (!b[1][1]) return 0; if (b[1][1] == b[0][0] ...