WeixiangYan/CodeTransOcean huggingface dataset:
Task: Giuga numbers


C++: #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 false;
    static constexpr unsigned int wheel[] = {4, 2, 4, 2, 4, 6, 2, 6};
    for (unsigned int p = 7, i = 0; p * p <= m; ++i) {
        if (!test_factor(p))
            return false;
        p += wheel[i & 7];
    }
    return m == 1 || (n / m - 1) % m == 0;
}

int main() {
    std::cout << "First 5 Giuga numbers:\n";
    
    for (unsigned int i = 0, n = 6; i < 5; n += 4) {
        if (is_giuga(n)) {
            std::cout << n << '\n';
            ++i;
        }
    }
}






Python: 

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:
                return False


if __name__ == '__main__':
    n = 3
    c = 0
    print("The first 4 Giuga numbers are: ")
    while c < 4:
        if isGiuga(n):
            c += 1
            print(n)
        n += 1
Task: Polynomial synthetic division


C++: 

#include <iostream>
#include <vector>
#include <string>
#include <cmath>



std::string frmtPolynomial(std::vector<int> polynomial, bool remainder = false)
{
	std::string r = "";

	if (remainder) 
	{
		r = " r: " + std::to_string(polynomial.back());
		polynomial.pop_back();
	}

	std::string formatted = "";
	
	int degree = polynomial.size() - 1;
	int d = degree;

	for (int i : polynomial)
	{
		if (d < degree)
		{
			if (i >= 0) 
			{
				formatted += " + ";
			}
			else
			{
				formatted += " - ";
			}
		}

		formatted += std::to_string(abs(i));

		if (d > 1)
		{
			formatted += "x^" + std::to_string(d);
		}
		else if (d == 1)
		{
			formatted += "x";
		}

		d--;
	}

	return formatted;
}



std::vector<int> syntheticDiv(std::vector<int> dividend, std::vector<int> divisor)
{
	std::vector<int> quotient;
	quotient = dividend;

	int normalizer = divisor[0];
	
	for (int i = 0; i < dividend.size() - (divisor.size() - 1); i++)
	{
		quotient[i] /= normalizer;
		int coef = quotient[i];

		if (coef != 0) 
		{
			for (int j = 1; j < divisor.size(); j++)
			{
				quotient[i + j] += -divisor[j] * coef;
			}
        }

	}

	return quotient;
}



int main(int argc, char **argv) 
{
	std::vector<int> dividend{ 1, -12, 0, -42};
	std::vector<int> divisor{ 1, -3};

	std::cout << frmtPolynomial(dividend) << "\n";
	std::cout << frmtPolynomial(divisor) << "\n";

	std::vector<int> quotient = syntheticDiv(dividend, divisor);

	std::cout << frmtPolynomial(quotient, true) << "\n";

}






Python: 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 = out[i]
        if coef != 0: 
            for j in xrange(1, len(divisor)): 
                                              
                out[i + j] += -divisor[j] * coef

    
    
    
    separator = -(len(divisor)-1)
    return out[:separator], out[separator:] 

if __name__ == '__main__':
    print("POLYNOMIAL SYNTHETIC DIVISION")
    N = [1, -12, 0, -42]
    D = [1, -3]
    print("  %s / %s  =" % (N,D), " %s remainder %s" % extended_synthetic_division(N, D))
Task: Odd words


C++: #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 : words) {
        out << std::right << std::setw(2) << n++ << ": "
            << std::left << std::setw(14) << pair.first
            << pair.second << '\n';
    }
}

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;
    }
    const int min_length = 5;
    std::string line;
    std::set<std::string> dictionary;
    while (getline(in, line)) {
        if (line.size() >= min_length)
            dictionary.insert(line);
    }

    word_list odd_words, even_words;

    for (const std::string& word : dictionary) {
        if (word.size() < min_length + 2*(min_length/2))
            continue;
        std::string odd_word, even_word;
        for (auto w = word.begin(); w != word.end(); ++w) {
            odd_word += *w;
            if (++w == word.end())
                break;
            even_word += *w;
        }

        if (dictionary.find(odd_word) != dictionary.end())
            odd_words.emplace_back(word, odd_word);

        if (dictionary.find(even_word) != dictionary.end())
            even_words.emplace_back(word, even_word);
    }

    std::cout << "Odd words:\n";
    print_words(std::cout, odd_words);

    std::cout << "\nEven words:\n";
    print_words(std::cout, even_words);

    return EXIT_SUCCESS;
}






Python: 

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:
        oddWordSet.add(word[::2])

[print(i) for i in sorted(oddWordSet)]
Task: Selectively replace multiple instances of a character within a string


C++: #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.empty())
    {
      *it = f->second.back();
      f->second.pop_back();
    }
  }

  std::cout << magic << "\n";
}






Python: 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 repdict[c] else c)
        seen[c] += 1
    return ''.join(newchars)

print('abracadabra ->', trstring('abracadabra', rep))
Task: Repunit primes


C++: #include <future>
#include <iomanip>
#include <iostream>
#include <vector>

#include <gmpxx.h>
#include <primesieve.hpp>

std::vector<uint64_t> repunit_primes(uint32_t base,
                                     const std::vector<uint64_t>& primes) {
    std::vector<uint64_t> result;
    for (uint64_t prime : primes) {
        mpz_class repunit(std::string(prime, '1'), base);
        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
            result.push_back(prime);
    }
    return result;
}

int main() {
    std::vector<uint64_t> primes;
    const uint64_t limit = 2700;
    primesieve::generate_primes(limit, &primes);
    std::vector<std::future<std::vector<uint64_t>>> futures;
    for (uint32_t base = 2; base <= 36; ++base) {
        futures.push_back(std::async(repunit_primes, base, primes));
    }
    std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
        std::cout << "Base " << std::setw(2) << base << ':';
        for (auto digits : futures[i].get())
            std::cout << ' ' << digits;
        std::cout << '\n';
    }
}






Python: 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))])
Task: Curzon numbers


C++: #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;
        base = (base * base) % mod;
    }
    return result;
}

bool is_curzon(uint64_t n, uint64_t k) {
    const uint64_t r = k * n;
    return modpow(k, n, r + 1) == r;
}

int main() {
    for (uint64_t k = 2; k <= 10; k += 2) {
        std::cout << "Curzon numbers with base " << k << ":\n";
        uint64_t count = 0, n = 1;
        for (; count < 50; ++n) {
            if (is_curzon(n, k)) {
                std::cout << std::setw(4) << n
                          << (++count % 10 == 0 ? '\n' : ' ');
            }
        }
        for (;;) {
            if (is_curzon(n, k))
                ++count;
            if (count == 1000)
                break;
            ++n;
        }
        std::cout << "1000th Curzon number with base " << k << ": " << n
                  << "\n\n";
    }
    return 0;
}






Python: 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(f'{c: 5,}', end='\n' if (i + 1) % 25 == 0 else '')
    print(f'    Thousandth Curzon with k = {k}: {curzons[999]}.\n')
Task: Ramanujan's constant


C++: #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)) * pi);
}

int main() {
    std::cout << "Ramanujan's constant using formula f(N) = exp(pi*sqrt(N)):\n"
        << std::setprecision(80) << f(163) << '\n';
    std::cout << "\nResult with last four Heegner numbers:\n";
    std::cout << std::setprecision(30);
    for (unsigned int n : {19, 43, 67, 163}) {
        auto x = f(n);
        auto c = ceil(x);
        auto pc = 100.0 * (x/c);
        std::cout << "f(" << n << ") = " << x << " = "
            << pc << "% of " << c << '\n';
    }
    return 0;
}






Python: 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(i))),(mp.pi*mp.sqrt(i)) - round(mp.pi*mp.sqrt(i))))
Task: Respond to an unknown method call


C++: 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();  
}






Python: 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))
        return method

example = Example()

example.foo()        
example.bar()        
example.grill()      
example.ding("dong")
Task: Joystick position


C++: #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\n"
#define HOME  "00000\r\n00+00\r\n00000\r\n"

int main() {
	clear();
	system("stty raw");

	printf(HOME);
	printf("space to exit; wasd to move\r\n");
	char c = 1;

	while(c) {
		c = getc(stdin);
		clear();

		switch (c)
		{
			case 'a':
				printf(LEFT);
				break;
			case 'd':
				printf(RIGHT);
				break;
			case 'w':
				printf(UP);
				break;
			case 's':
				printf(DOWN);
				break;
			case ' ':
				c = 0;
				break;
			default:
				printf(HOME);
		};

		printf("space to exit; wasd key to move\r\n");
	}

	system("stty cooked");
	system("clear"); 
	return 1;
}






Python: 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")


frameRect = pygame.Rect((45, 45), (510, 510))


crosshair = pygame.surface.Surface((10, 10))
crosshair.fill(pygame.Color("magenta"))
pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0)
crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL)
crosshair = crosshair.convert()


writer = pygame.font.Font(pygame.font.get_default_font(), 15)
buttons = {}
for b in range(joy.get_numbuttons()):
    buttons[b] = [
        writer.render(
            hex(b)[2:].upper(),
            1,
            pygame.Color("red"),
            pygame.Color("black")
        ).convert(),
        
        
        ((15*b)+45, 560)
    ]

while True:
    
    pygame.event.pump()
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    
    screen.fill(pygame.Color("black"))

    
    x = joy.get_axis(0)
    y = joy.get_axis(1)

    
    
    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))
    pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1)

    
    for b in range(joy.get_numbuttons()):
        if joy.get_button(b):
            screen.blit(buttons[b][0], buttons[b][1])

    
    pygame.display.flip()
    clk.tick(40)
Task: Earliest difference between prime gaps


C++: #include <iostream>
#include <locale>
#include <unordered_map>

#include <primesieve.hpp>

class prime_gaps {
public:
    prime_gaps() { last_prime_ = iterator_.next_prime(); }
    uint64_t find_gap_start(uint64_t gap);
private:
    primesieve::iterator iterator_;
    uint64_t last_prime_;
    std::unordered_map<uint64_t, uint64_t> gap_starts_;
};

uint64_t prime_gaps::find_gap_start(uint64_t gap) {
    auto i = gap_starts_.find(gap);
    if (i != gap_starts_.end())
        return i->second;
    for (;;) {
        uint64_t prev = last_prime_;
        last_prime_ = iterator_.next_prime();
        uint64_t diff = last_prime_ - prev;
        gap_starts_.emplace(diff, prev);
        if (gap == diff)
            return prev;
    }
}

int main() {
    std::cout.imbue(std::locale(""));
    const uint64_t limit = 100000000000;
    prime_gaps pg;
    for (uint64_t pm = 10, gap1 = 2;;) {
        uint64_t start1 = pg.find_gap_start(gap1);
        uint64_t gap2 = gap1 + 2;
        uint64_t start2 = pg.find_gap_start(gap2);
        uint64_t diff = start2 > start1 ? start2 - start1 : start1 - start2;
        if (diff > pm) {
            std::cout << "Earliest difference > " << pm
                      << " between adjacent prime gap starting primes:\n"
                      << "Gap " << gap1 << " starts at " << start1 << ", gap "
                      << gap2 << " starts at " << start2 << ", difference is "
                      << diff << ".\n\n";
            if (pm == limit)
                break;
            pm *= 10;
        } else {
            gap1 = gap2;
        }
    }
}






Python: 

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[GAP1]
    GAP2 = GAP1 + 2
    if GAP2 not in gapstarts:
        GAP1 = GAP2 + 2
        continue
    start2 = gapstarts[GAP2]
    diff = abs(start2 - start1)
    if diff > PM:
        print(f"Earliest difference >{PM: ,} between adjacent prime gap starting primes:")
        print(f"Gap {GAP1} starts at{start1: ,}, gap {GAP2} starts at{start2: ,}, difference is{diff: ,}.\n")
        if PM == LIMIT:
            break
        PM *= 10
    else:
        GAP1 = GAP2
Task: Ormiston pairs


C++: #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_;
            auto digits = digits_;
            prime_ = pi_.next_prime();
            digits_ = get_digits(prime_);
            if (digits_ == digits)
                return std::make_pair(prime, prime_);
        }
    }

private:
    static std::array<int, 10> get_digits(uint64_t n) {
        std::array<int, 10> result = {};
        for (; n > 0; n /= 10)
            ++result[n % 10];
        return result;
    }
    primesieve::iterator pi_;
    uint64_t prime_;
    std::array<int, 10> digits_;
};

int main() {
    ormiston_pair_generator generator;
    int count = 0;
    std::cout << "First 30 Ormiston pairs:\n";
    for (; count < 30; ++count) {
        auto [p1, p2] = generator.next_pair();
        std::cout << '(' << std::setw(5) << p1 << ", " << std::setw(5) << p2
                  << ')' << ((count + 1) % 3 == 0 ? '\n' : ' ');
    }
    std::cout << '\n';
    for (uint64_t limit = 1000000; limit <= 1000000000; ++count) {
        auto [p1, p2] = generator.next_pair();
        if (p1 > limit) {
            std::cout << "Number of Ormiston pairs < " << limit << ": " << count
                      << '\n';
            limit *= 10;
        }
    }
}






Python: 

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 enumerate(ORMISTONS):
    if i < 30:
        print(f'({o[0] : 6} {o[1] : 6} )',
              end='\n' if (i + 1) % 5 == 0 else '  ')
    else:
        break

print(len(ORMISTONS), 'is the count of Ormiston pairs up to one million.')
Task: Harmonic series


C++: #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, ++n_);
        return result;
    }
    void reset() {
        n_ = 1;
        term_ = 1;
    }
private:
    integer n_ = 1;
    rational term_ = 1;
};

int main() {
    std::cout << "First 20 harmonic numbers:\n";
    harmonic_generator hgen;
    for (int i = 1; i <= 20; ++i)
        std::cout << std::setw(2) << i << ". " << hgen.next() << '\n';
    
    rational h;
    for (int i = 1; i <= 80; ++i)
        h = hgen.next();
    std::cout << "\n100th harmonic number: " << h << "\n\n";

    int n = 1;
    hgen.reset();
    for (int i = 1; n <= 10; ++i) {
        if (hgen.next() > n)
            std::cout << "Position of first term > " << std::setw(2) << n++ << ": " << i << '\n';
    }
}






Python: 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, '/', d)
Task: Continued fraction_Arithmetic_G(matrix ng, continued fraction n)


C++: 
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 (b1==0 and b==0) return false;
    if (b1==0 or b==0) return true; else thisTerm = a/b;
    if (thisTerm==(int)(a1/b1)){
      t=a; a=b; b=t-b*thisTerm; t=a1; a1=b1; b1=t-b1*thisTerm;
      haveTerm=true; return false;
    }
    return true;
  }
  void consumeTerm(){a=a1; b=b1;}
  void consumeTerm(int n){t=a; a=a1; a1=t+a1*n; t=b; b=b1; b1=t+b1*n;}
  public:
  NG_4(int a1, int a, int b1, int b): a1(a1), a(a), b1(b1), b(b){}
};

class NG : public ContinuedFraction {
  private:
   matrixNG* ng;
   ContinuedFraction* n[2];
  public:
  NG(NG_4* ng, ContinuedFraction* n1): ng(ng){n[0] = n1;}
  NG(NG_8* ng, ContinuedFraction* n1, ContinuedFraction* n2): ng(ng){n[0] = n1; n[1] = n2;}
  const int nextTerm() {ng->haveTerm = false; return ng->thisTerm;}
  const bool moreTerms(){
    while(ng->needTerm()) if(n[ng->cfn]->moreTerms()) ng->consumeTerm(n[ng->cfn]->nextTerm()); else ng->consumeTerm();
    return ng->haveTerm;
  }
};






Python: 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//self.b == self.a1//self.b1

  @property
  def egress(self):
    n = self.a // self.b
    self.a,  self.b  = self.b,  self.a  - self.b  * n
    self.a1, self.b1 = self.b1, self.a1 - self.b1 * n
    return n

  @property
  def egress_done(self):
    if self.needterm: self.a, self.b = self.a1, self.b1
    return self.egress

  @property
  def done(self):
    return self.b == 0 and self.b1 == 0
Task: Calkin-Wilf sequence


C++: #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<unsigned long> continued_fraction(const rational& r) {
    unsigned long a = r.numerator();
    unsigned long b = r.denominator();
    std::vector<unsigned long> result;
    do {
        result.push_back(a/b);
        unsigned long c = a;
        a = b;
        b = c % b;
    } while (a != 1);
    if (result.size() > 0 && result.size() % 2 == 0) {
        --result.back();
        result.push_back(1);
    }
    return result;
}

unsigned long term_number(const rational& r) {
    unsigned long result = 0;
    unsigned long d = 1;
    unsigned long p = 0;
    for (unsigned long n : continued_fraction(r)) {
        for (unsigned long i = 0; i < n; ++i, ++p)
            result |= (d << p);
        d = !d;
    }
    return result;
}

int main() {
    rational term = 1;
    std::cout << "First 20 terms of the Calkin-Wilf sequence are:\n";
    for (int i = 1; i <= 20; ++i) {
        std::cout << std::setw(2) << i << ": " << term << '\n';
        term = calkin_wilf_next(term);
    }
    rational r(83116, 51639);
    std::cout << r << " is the " << term_number(r) << "th term of the sequence.\n";
}






Python: 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, divmod(num, den)
        yield digit

def get_term_num(rational):
    ans, dig, pwr = 0, 1, 0
    for n in r2cf(rational):
        for _ in range(n):
            ans |= dig << pwr
            pwr += 1
        dig ^= 1
    return ans

          
if __name__ == '__main__':
    print('TERMS 1..20: ', ', '.join(str(x) for x in islice(cw(), 20)))
    x = Fraction(83116, 51639)
    print(f"\n{x} is the {get_term_num(x):_}'th term.")