WeixiangYan/CodeTransOcean huggingface dataset:
Task: Sorting algorithms_Bead sort


C++: 



#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 (myints, myints + n);

    cout << "#1 Beads falling down: ";
    for (int i=0; i < fifth.size(); i++)
        distribute (fifth[i], list);
    cout << '\n';

    cout << "\nBeads on their sides: ";
    for (int i=0; i < list.size(); i++)
        cout << " " << list[i];
    cout << '\n';

    

    cout << "#2 Beads right side up: ";
    for (int i=0; i < list.size(); i++)
        distribute (list[i], list2);
    cout << '\n';

    return list2;
}

int main() {
    int myints[] = {734,3,1,24,324,324,32,432,42,3,4,1,1};
	vector<int> sorted = beadSort(myints, sizeof(myints)/sizeof(int));
	cout << "Sorted list/array: ";
	for(unsigned int i=0; i<sorted.size(); i++)
		cout << sorted[i] << ' ';
}
Task: Casting out nines


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 - ((double)c2/c1)*100 << "%" <<std::endl;
	return 0;
}
Task: Execute HQ9+


C++: void runCode(string code)
{
    int c_len = code.length();
    unsigned accumulator=0;
    int bottles;
    for(int i=0;i<c_len;i++)
    {
        switch(code[i])
        {
            case 'Q':
                cout << code << endl;
                break;

            case 'H':
                cout << "Hello, world!" << endl;
                break;

            case '9':
                
                bottles = 99;
                do {
                    cout << bottles << " bottles of beer on the wall" << endl;
                    cout << bottles << " bottles of beer" << endl;
                    cout << "Take one down, pass it around" << endl;
                    cout << --bottles << " bottles of beer on the wall" << endl << endl;
                } while( bottles > 0 );
                break;

            case '+':
                
                accumulator++;
                break;
        }
    }
};
Task: Tau function


C++: #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 *= count;
    }
    
    if (n > 1)
        total *= 2;
    return total;
}

int main() {
    const unsigned int limit = 100;
    std::cout << "Count of divisors for the first " << limit << " positive integers:\n";
    for (unsigned int n = 1; n <= limit; ++n) {
        std::cout << std::setw(3) << divisor_count(n);
        if (n % 20 == 0)
            std::cout << '\n';
    }
}
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;
}
Task: Mertens function


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(mertens_numbers(max));
    std::cout << "First 199 Mertens numbers:\n";
    for (int i = 0, column = 0; i < 200; ++i) {
        if (column > 0)
            std::cout << ' ';
        if (i == 0)
            std::cout << "  ";
        else
            std::cout << std::setw(2) << m[i];
        ++column;
        if (column == 20) {
            std::cout << '\n';
            column = 0;
        }
    }
    int zero = 0, cross = 0, previous = 0;
    for (int i = 1; i <= max; ++i) {
        if (m[i] == 0) {
            ++zero;
            if (previous != 0)
                ++cross;
        }
        previous = m[i];
    }
    std::cout << "M(n) is zero " << zero << " times for 1 <= n <= 1000.\n";
    std::cout << "M(n) crosses zero " << cross << " times for 1 <= n <= 1000.\n";
    return 0;
}
Task: Erdős-primes


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_prime_generator::next() {
    uint64_t prime;
    for (;;) {
        prime = iter_.next_prime();
        primes_.insert(prime);
        if (erdos(prime))
            break;
    }
    return prime;
}

bool erdos_prime_generator::erdos(uint64_t p) const {
    for (uint64_t k = 1, f = 1; f < p; ++k, f *= k) {
        if (primes_.find(p - f) != primes_.end())
            return false;
    }
    return true;
}

int main() {
    std::wcout.imbue(std::locale(""));
    erdos_prime_generator epgen;
    const int max_print = 2500;
    const int max_count = 7875;
    uint64_t p;
    std::wcout << L"Erd\x151s primes less than " << max_print << L":\n";
    for (int count = 1; count <= max_count; ++count) {
        p = epgen.next();
        if (p < max_print)
            std::wcout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' ');
    }
    std::wcout << L"\n\nThe " << max_count << L"th Erd\x151s prime is " << p << L".\n";
    return 0;
}
Task: Perfect totient numbers


C++: #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)
                continue;
            for (int j = i; j <= max; j += i)
                totient_[j] -= totient_[j] / i;
        }
    }
    int totient(int n) const {
        assert (n >= 1 && n < totient_.size());
        return totient_[n];
    }
    bool is_prime(int n) const {
        return totient(n) == n - 1;
    }
private:
    std::vector<int> totient_;
};

bool perfect_totient_number(const totient_calculator& tc, int n) {
    int sum = 0;
    for (int m = n; m > 1; ) {
        int t = tc.totient(m);
        sum += t;
        m = t;
    }
    return sum == n;
}

int main() {
    totient_calculator tc(10000);
    int count = 0, n = 1;
    std::cout << "First 20 perfect totient numbers:\n";
    for (; count < 20; ++n) {
        if (perfect_totient_number(tc, n))  {
            if (count > 0)
                std::cout << ' ';
            ++count;
            std::cout << n;
        }
    }
    std::cout << '\n';
    return 0;
}
Task: Two sum


C++: #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);
		}
		m[numbers[i]] = i;
	}

	return make_pair(-1, -1);
}

int main() {
	auto numbers = vector<int>{ 0, 2, 11, 19, 90 };
	const int sum = 21;

	auto ts = twoSum(numbers, sum);
	if (ts.first != -1) {
		cout << "{" << ts.first << ", " << ts.second << "}" << endl;
	} else {
		cout << "no result" << endl;
	}

	return 0;
}
Task: Unprimeable numbers


C++: #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;
    for (; index > 0; p *= 10, n /= 10, --index)
        changed += p * (n % 10);
    changed += (10 * (n/10) + new_digit) * p;
    return changed;
}


bool unprimeable(const prime_sieve& sieve, integer n) {
    if (sieve.is_prime(n))
        return false;
    int d = count_digits(n);
    for (int i = 0; i < d; ++i) {
        for (int j = 0; j <= 9; ++j) {
            integer m = change_digit(n, i, j);
            if (m != n && sieve.is_prime(m))
                return false;
        }
    }
    return true;
}

int main() {
    const integer limit = 10000000;
    prime_sieve sieve(limit);

    
    std::cout.imbue(std::locale(""));

    std::cout << "First 35 unprimeable numbers:\n";
    integer n = 100;
    integer lowest[10] = { 0 };
    for (int count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
        if (unprimeable(sieve, n)) {
            if (count < 35) {
                if (count != 0)
                    std::cout << ", ";
                std::cout << n;
            }
            ++count;
            if (count == 600)
                std::cout << "\n600th unprimeable number: " << n << '\n';
            int last_digit = n % 10;
            if (lowest[last_digit] == 0) {
                lowest[last_digit] = n;
                ++found;
            }
        }
    }
    for (int i = 0; i < 10; ++i)
        std::cout << "Least unprimeable number ending in " << i << ": " << lowest[i] << '\n';
    return 0;
}
Task: Tau number


C++: #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 *= count;
    }
    
    if (n > 1)
        total *= 2;
    return total;
}

int main() {
    const unsigned int limit = 100;
    std::cout << "The first " << limit << " tau numbers are:\n";
    unsigned int count = 0;
    for (unsigned int n = 1; count < limit; ++n) {
        if (n % divisor_count(n) == 0) {
            std::cout << std::setw(6) << n;
            ++count;
            if (count % 10 == 0)
                std::cout << '\n';
        }
    }
}
Task: Primes whose sum of digits is 25


C++: #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;
    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)
            return false;
    }
    return true;
}

int digit_sum(int n) {
    int sum = 0;
    for (; n > 0; n /= 10)
        sum += n % 10;
    return sum;
}

int count_all(const std::string& str, int rem) {
    int count = 0;
    if (rem == 0) {
        switch (str.back()) {
        case '1':
        case '3':
        case '7':
        case '9':
            if (is_probably_prime(mpz_class(str)))
                ++count;
            break;
        default:
            break;
        }
    } else {
        for (int i = 1; i <= std::min(9, rem); ++i)
            count += count_all(str + char('0' + i), rem - i);
    }
    return count;
}

int main() {
    std::cout.imbue(std::locale(""));
    const int limit = 5000;
    std::cout << "Primes < " << limit << " whose digits sum to 25:\n";
    int count = 0;
    for (int p = 1; p < limit; ++p) {
        if (digit_sum(p) == 25 && is_prime(p)) {
            ++count;
            std::cout << std::setw(6) << p << (count % 10 == 0 ? '\n' : ' ');
        }
    }
    std::cout << '\n';

    auto start = std::chrono::steady_clock::now();
    count = count_all("", 25);
    auto end = std::chrono::steady_clock::now();
    std::cout << "\nThere are " << count
              << " primes whose digits sum to 25 and include no zeros.\n";
    std::cout << "Time taken: "
              << std::chrono::duration<double>(end - start).count() << "s\n";
    return 0;
}
Task: Numbers with prime digits whose sum is 13


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)
        printf("%d%d ", get<0>(i), x);
      else if (sum < 12) w.push_back({get<0>(i) * 10 + x, sum}); }
  return 0; }
Task: Circular primes


C++: #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;
    return out.str();
}

bool is_circular_prime(const integer& p) {
    if (!is_prime(p))
        return false;
    std::string str(to_string(p));
    for (size_t i = 0, n = str.size(); i + 1 < n; ++i) {
        std::rotate(str.begin(), str.begin() + 1, str.end());
        integer p2(str, 10);
        if (p2 < p || !is_prime(p2))
            return false;
    }
    return true;
}

integer next_repunit(const integer& n) {
    integer p = 1;
    while (p < n)
        p = 10 * p + 1;
    return p;
}

integer repunit(int digits) {
    std::string str(digits, '1');
    integer p(str);
    return p;
}

void test_repunit(int digits) {
    if (is_prime(repunit(digits), 10))
        std::cout << "R(" << digits << ") is probably prime\n";
    else
        std::cout << "R(" << digits << ") is not prime\n";
}

int main() {
    integer p = 2;
    std::cout << "First 19 circular primes:\n";
    for (int count = 0; count < 19; ++p) {
        if (is_circular_prime(p)) {
            if (count > 0)
                std::cout << ", ";
            std::cout << p;
            ++count;
        }
    }
    std::cout << '\n';
    std::cout << "Next 4 circular primes:\n";
    p = next_repunit(p);
    std::string str(to_string(p));
    int digits = str.size();
    for (int count = 0; count < 4; ) {
        if (is_prime(p, 15)) {
            if (count > 0)
                std::cout << ", ";
            std::cout << "R(" << digits << ")";
            ++count;
        }
        p = repunit(++digits);
    }
    std::cout << '\n';
    test_repunit(5003);
    test_repunit(9887);
    test_repunit(15073);
    test_repunit(25031);
    test_repunit(35317);
    test_repunit(49081);
    return 0;
}
Task: Modulinos


C++: int meaning_of_life();
Task: Nice primes


C++: #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)
            return false;
    }
    return true;
}

unsigned int digital_root(unsigned int n) {
    return n == 0 ? 0 : 1 + (n - 1) % 9;
}

int main() {
    const unsigned int from = 500, to = 1000;
    std::cout << "Nice primes between " << from << " and " << to << ":\n";
    unsigned int count = 0;
    for (unsigned int n = from; n < to; ++n) {
        if (is_prime(digital_root(n)) && is_prime(n)) {
            ++count;
            std::cout << n << (count % 10 == 0 ? '\n' : ' ');
        }
    }
    std::cout << '\n' << count << " nice primes found.\n";
}
Task: Find the last Sunday of each month


C++: #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:    "; 
	m[8]  = "SEPTEMBER: "; m[9]  = "OCTOBER:   "; m[10] = "NOVEMBER:  "; m[11] = "DECEMBER:  "; 
    }

    void findLastSunday( int y )
    {
	year = y;
	isleapyear();

	int days[] = { 31, isleap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
		d;
	for( int i = 0; i < 12; i++ )
	{
	    d = days[i];
	    while( true )
	    {
		if( !getWeekDay( i, d ) ) break;
		d--;
	    }
	    lastDay[i] = d;
	}

	display();
    }

private:
    void isleapyear()
    {
	isleap = false;
	if( !( year % 4 ) )
	{
	    if( year % 100 ) isleap = true;
	    else if( !( year % 400 ) ) isleap = true;
	}
    }

    void display()
    {
	system( "cls" );
	cout << "  YEAR " << year << endl << "=============" << endl;
	for( int x = 0; x < 12; x++ )
	    cout << m[x] << lastDay[x] << endl;

	cout << endl << endl;
    }

    int getWeekDay( int m, int d )
    {
	int y = year;

	int f = y + d + 3 * m - 1;
	m++;
	if( m < 3 ) y--;
	else f -= int( .4 * m + 2.3 );

	f += int( y / 4 ) - int( ( y / 100 + 1 ) * 0.75 );
	f %= 7;

	return f;
    }

    int lastDay[12], year;
    string m[12];
    bool isleap;
};

int main( int argc, char* argv[] )
{
    int y;
    lastSunday ls;

    while( true )
    {
	system( "cls" );
	cout << "Enter the year( yyyy ) --- ( 0 to quit ): "; 
	cin >> y;
	if( !y ) return 0;

	ls.findLastSunday( y );

	system( "pause" );
    }
    return 0;
}
Task: Random Latin squares


C++: #include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#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 << ", ";
        os << *it;
        it = std::next(it);
    }
    return os << ']';
}

void printSquare(const std::vector<std::vector<int>> &latin) {
    for (auto &row : latin) {
        std::cout << row << '\n';
    }
    std::cout << '\n';
}

void latinSquare(int n) {
    if (n <= 0) {
        std::cout << "[]\n";
        return;
    }

    
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    auto g = std::default_random_engine(seed);

    std::vector<std::vector<int>> latin;
    for (int i = 0; i < n; ++i) {
        std::vector<int> inner;
        for (int j = 0; j < n; ++j) {
            inner.push_back(j);
        }
        latin.push_back(inner);
    }
    
    std::shuffle(latin[0].begin(), latin[0].end(), g);

    
    for (int i = 1; i < n - 1; ++i) {
        bool shuffled = false;

        while (!shuffled) {
            std::shuffle(latin[i].begin(), latin[i].end(), g);
            for (int k = 0; k < i; ++k) {
                for (int j = 0; j < n; ++j) {
                    if (latin[k][j] == latin[i][j]) {
                        goto shuffling;
                    }
                }
            }
            shuffled = true;

        shuffling: {}
        }
    }

    
    for (int j = 0; j < n; ++j) {
        std::vector<bool> used(n, false);
        for (int i = 0; i < n - 1; ++i) {
            used[latin[i][j]] = true;
        }
        for (int k = 0; k < n; ++k) {
            if (!used[k]) {
                latin[n - 1][j] = k;
                break;
            }
        }
    }

    printSquare(latin);
}

int main() {
    latinSquare(5);
    latinSquare(5);
    latinSquare(10);
    return 0;
}
Task: RPG attributes generator


C++: #include <algorithm>
#include <ctime>
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
    srand(time(0));
    
    unsigned int attributes_total = 0;
    unsigned int count = 0;
    int attributes[6] = {};
    int rolls[4] = {};
    
    while(attributes_total < 75 || count < 2)
    {
        attributes_total = 0;
        count = 0;
        
        for(int attrib = 0; attrib < 6; attrib++)
        {            
            for(int roll = 0; roll < 4; roll++)
            {
                rolls[roll] = 1 + (rand() % 6);
            }
            
            sort(rolls, rolls + 4);
            int roll_total = rolls[1] + rolls[2] + rolls[3];            
                        
            attributes[attrib] = roll_total;
            attributes_total += roll_total;
            
            if(roll_total >= 15) count++;
        }
    }
    
    cout << "Attributes generated : [";
    cout << attributes[0] << ", ";
    cout << attributes[1] << ", ";
    cout << attributes[2] << ", ";
    cout << attributes[3] << ", ";
    cout << attributes[4] << ", ";
    cout << attributes[5];
    
    cout << "]\nTotal: " << attributes_total;
    cout << ", Values above 15 : " << count;
    
    return 0;
}
Task: Longest increasing subsequence


C++: #include <vector>
#include <list>
#include <algorithm>
#include <iostream>

template <typename T>
struct Node {
    T value;
    Node* prev_node;
};

template <typename Container>
Container lis(const Container& values) {
    using E = typename Container::value_type;
    using NodePtr = Node<E>*;
    using ConstNodePtr = const NodePtr;

    std::vector<NodePtr> pileTops;
    std::vector<Node<E>> nodes(values.size());

    
    auto cur_node = std::begin(nodes);
    for (auto cur_value = std::begin(values); cur_value != std::end(values); ++cur_value, ++cur_node)
    {
        auto node = &*cur_node;
        node->value = *cur_value;

        
        auto lb = std::lower_bound(pileTops.begin(), pileTops.end(), node,
            [](ConstNodePtr& node1, ConstNodePtr& node2) -> bool { return node1->value < node2->value; });

        if (lb != pileTops.begin())
            node->prev_node = *std::prev(lb);

        if (lb == pileTops.end())
            pileTops.push_back(node);
        else
            *lb = node;
    }

    
    
    Container result(pileTops.size());
    auto r = std::rbegin(result);

    for (NodePtr node = pileTops.back(); node != nullptr; node = node->prev_node, ++r)
        *r = node->value;

    return result;
}

template <typename Container>
void show_lis(const Container& values)
{
    auto&& result = lis(values);
    for (auto& r : result) {
        std::cout << r << ' ';
    }
    std::cout << std::endl;
}

int main() 
{
    show_lis(std::list<int> { 3, 2, 6, 4, 5, 1 });
    show_lis(std::vector<int> { 0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15 });
}