WeixiangYan/CodeTransOcean huggingface dataset:
Task: First power of 2 that has leading decimal digits of 12


C++: 

#include <string>
#include <chrono>
#include <cmath>
#include <locale>

using namespace std;
using namespace chrono;


unsigned int js(int l, int n) {
  unsigned int res = 0, f = 1; 
  double lf = log(2) / log(10), ip;
  for (int i = l; i > 10; i /= 10) f *= 10;
  while (n > 0)
    if ((int)(f * pow(10, modf(++res * lf, &ip))) == l) n--;
  return res;
}


unsigned int gi(int ld, int n) {
  string Ls = to_string(ld);
  unsigned int res = 0, count = 0; unsigned long long f = 1;
  for (int i = 1; i <= 18 - Ls.length(); i++) f *= 10;
  const unsigned long long ten18 = 1e18; unsigned long long probe = 1;
  do {
    probe <<= 1; res++; if (probe >= ten18) {
      do {
        if (probe >= ten18) probe /= 10;
        if (probe / f == ld) if (++count >= n) { count--; break; }
        probe <<= 1; res++;
      } while (1);
    }
    string ps = to_string(probe);
    if (ps.substr(0, min(Ls.length(), ps.length())) == Ls) if (++count >= n) break;
  } while (1);
  return res;
}


unsigned int pa(int ld, int n) {
  const double L_float64 = pow(2, 64);
  const unsigned long long Log10_2_64 = (unsigned long long)(L_float64 * log(2) / log(10));
  double Log10Num; unsigned long long LmtUpper, LmtLower, Frac64;
  int res = 0, dgts = 1, cnt;
  for (int i = ld; i >= 10; i /= 10) dgts *= 10;
  Log10Num = log((ld + 1.0) / dgts) / log(10);
  
  if (Log10Num >= 0.5) {
    LmtUpper = (ld + 1.0) / dgts < 10.0 ? (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2) : 0;
    Log10Num = log((double)ld / dgts) / log(10);
    LmtLower = (unsigned long long)(Log10Num * (L_float64 * 0.5)) * 2 + (unsigned long long)(Log10Num * 2);
  } else {
    LmtUpper = (unsigned long long)(Log10Num * L_float64);    
    LmtLower = (unsigned long long)(log((double)ld / dgts) / log(10) * L_float64);
  }
  cnt = 0; Frac64 = 0; if (LmtUpper != 0) {
    do {
      res++; Frac64 += Log10_2_64;
      if ((Frac64 >= LmtLower) & (Frac64 < LmtUpper))
        if (++cnt >= n) break;
    } while (1);
  } else { 
    do {
      res++; Frac64 += Log10_2_64;
      if (Frac64 >= LmtLower) if (++cnt >= n) break;
    } while (1);
  };
  return res;
}

int params[] = { 12, 1, 12, 2, 123, 45, 123, 12345, 123, 678910, 99, 1 };

void doOne(string name, unsigned int (*func)(int a, int b)) {
  printf("%s version:\n", name.c_str());
  auto start = steady_clock::now();
  for (int i = 0; i < size(params); i += 2)
    printf("p(%3d, %6d) = %'11u\n", params[i], params[i + 1], func(params[i], params[i + 1]));
  printf("Took %f seconds\n\n", duration<double>(steady_clock::now() - start).count());
}

int main() {
  setlocale(LC_ALL, ""); 
  doOne("java simple", js);
  doOne("go integer", gi);
  doOne("pascal alternative", pa);
}
Task: N-smooth numbers


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

std::vector<uint64_t> primes;
std::vector<uint64_t> smallPrimes;

template <typename T>
std::ostream &operator <<(std::ostream &os, const std::vector<T> &v) {
    auto it = v.cbegin();
    auto end = v.cend();

    os << '[';

    if (it != end) {
        os << *it;
        it = std::next(it);
    }

    for (; it != end; it = std::next(it)) {
        os << ", " << *it;
    }

    return os << ']';
}

bool isPrime(uint64_t value) {
    if (value < 2) return false;

    if (value % 2 == 0) return value == 2;
    if (value % 3 == 0) return value == 3;

    if (value % 5 == 0) return value == 5;
    if (value % 7 == 0) return value == 7;

    if (value % 11 == 0) return value == 11;
    if (value % 13 == 0) return value == 13;

    if (value % 17 == 0) return value == 17;
    if (value % 19 == 0) return value == 19;

    if (value % 23 == 0) return value == 23;

    uint64_t t = 29;
    while (t * t < value) {
        if (value % t == 0) return false;
        value += 2;

        if (value % t == 0) return false;
        value += 4;
    }

    return true;
}

void init() {
    primes.push_back(2);
    smallPrimes.push_back(2);

    uint64_t i = 3;
    while (i <= 521) {
        if (isPrime(i)) {
            primes.push_back(i);
            if (i <= 29) {
                smallPrimes.push_back(i);
            }
        }
        i += 2;
    }
}

std::vector<uint64_t> nSmooth(uint64_t n, size_t size) {
    if (n < 2 || n>521) {
        throw std::runtime_error("n must be between 2 and 521");
    }
    if (size <= 1) {
        throw std::runtime_error("size must be at least 1");
    }

    uint64_t bn = n;
    if (primes.cend() == std::find(primes.cbegin(), primes.cend(), bn)) {
        throw std::runtime_error("n must be a prime number");
    }

    std::vector<uint64_t> ns(size, 0);
    ns[0] = 1;

    std::vector<uint64_t> next;
    for (auto prime : primes) {
        if (prime > bn) {
            break;
        }
        next.push_back(prime);
    }

    std::vector<size_t> indicies(next.size(), 0);
    for (size_t m = 1; m < size; m++) {
        ns[m] = *std::min_element(next.cbegin(), next.cend());
        for (size_t i = 0; i < indicies.size(); i++) {
            if (ns[m] == next[i]) {
                indicies[i]++;
                next[i] = primes[i] * ns[indicies[i]];
            }
        }
    }

    return ns;
}

int main() {
    init();

    for (auto i : smallPrimes) {
        std::cout << "The first " << i << "-smooth numbers are:\n";
        std::cout << nSmooth(i, 25) << '\n';
        std::cout << '\n';
    }

    
    for (size_t i = 0; i < smallPrimes.size(); i++) {
        if (i < 1) continue;
        auto p = smallPrimes[i];

        auto v = nSmooth(p, 3002);
        v.erase(v.begin(), v.begin() + 2999);

        std::cout << "The 30,000th to 30,019th " << p << "-smooth numbers are:\n";
        std::cout << v << '\n';
        std::cout << '\n';
    }

    return 0;
}
Task: Burrows–Wheeler transform


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

const int STX = 0x02;
const int ETX = 0x03;

void rotate(std::string &a) {
    char t = a[a.length() - 1];
    for (int i = a.length() - 1; i > 0; i--) {
        a[i] = a[i - 1];
    }
    a[0] = t;
}

std::string bwt(const std::string &s) {
    for (char c : s) {
        if (c == STX || c == ETX) {
            throw std::runtime_error("Input can't contain STX or ETX");
        }
    }

    std::string ss;
    ss += STX;
    ss += s;
    ss += ETX;

    std::vector<std::string> table;
    for (size_t i = 0; i < ss.length(); i++) {
        table.push_back(ss);
        rotate(ss);
    }
    
    std::sort(table.begin(), table.end());

    std::string out;
    for (auto &s : table) {
        out += s[s.length() - 1];
    }
    return out;
}

std::string ibwt(const std::string &r) {
    int len = r.length();
    std::vector<std::string> table(len);
    for (int i = 0; i < len; i++) {
        for (int j = 0; j < len; j++) {
            table[j] = r[j] + table[j];
        }
        std::sort(table.begin(), table.end());
    }
    for (auto &row : table) {
        if (row[row.length() - 1] == ETX) {
            return row.substr(1, row.length() - 2);
        }
    }
    return {};
}

std::string makePrintable(const std::string &s) {
    auto ls = s;
    for (auto &c : ls) {
        if (c == STX) {
            c = '^';
        } else if (c == ETX) {
            c = '|';
        }
    }
    return ls;
}

int main() {
    auto tests = {
        "banana",
        "appellee",
        "dogwood",
        "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
        "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
        "\u0002ABC\u0003"
    };

    for (auto &test : tests) {
        std::cout << makePrintable(test) << "\n";
        std::cout << " --> ";

        std::string t;
        try {
            t = bwt(test);
            std::cout << makePrintable(t) << "\n";
        } catch (std::runtime_error &e) {
            std::cout << "Error " << e.what() << "\n";
        }

        std::string r = ibwt(t);
        std::cout << " --> " << r << "\n\n";
    }

    return 0;
}
Task: Faulhaber's triangle


C++: #include <exception>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <sstream>
#include <vector>
 
class Frac {
public:

	Frac() : num(0), denom(1) {}

	Frac(int n, int d) {
		if (d == 0) {
			throw std::runtime_error("d must not be zero");
		}

		int sign_of_d = d < 0 ? -1 : 1;
		int g = std::gcd(n, d);

        num = sign_of_d * n / g;
        denom = sign_of_d * d / g;
	}
 
	Frac operator-() const {
		return Frac(-num, denom);
	}
 
	Frac operator+(const Frac& rhs) const {
		return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
	}
 
	Frac operator-(const Frac& rhs) const {
		return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
	}
 
	Frac operator*(const Frac& rhs) const {
		return Frac(num*rhs.num, denom*rhs.denom);
	}

	Frac operator*(int rhs) const {
		return Frac(num * rhs, denom);
	}

	friend std::ostream& operator<<(std::ostream&, const Frac&);
 
private:
	int num;
	int denom;
};
 
std::ostream & operator<<(std::ostream & os, const Frac &f) {
	if (f.num == 0 || f.denom == 1) {
		return os << f.num;
	}
 
	std::stringstream ss;
	ss << f.num << "/" << f.denom;
	return os << ss.str();
}
 
Frac bernoulli(int n) {
	if (n < 0) {
		throw std::runtime_error("n may not be negative or zero");
	}
 
	std::vector<Frac> a;
	for (int m = 0; m <= n; m++) {
		a.push_back(Frac(1, m + 1));
		for (int j = m; j >= 1; j--) {
			a[j - 1] = (a[j - 1] - a[j]) * j;
		}
	}
 
	
	if (n != 1) return a[0];
	return -a[0];
}
 
int binomial(int n, int k) {
	if (n < 0 || k < 0 || n < k) {
		throw std::runtime_error("parameters are invalid");
	}
	if (n == 0 || k == 0) return 1;
 
	int num = 1;
	for (int i = k + 1; i <= n; i++) {
		num *= i;
	}
 
	int denom = 1;
	for (int i = 2; i <= n - k; i++) {
		denom *= i;
	}
 
	return num / denom;
}
 
std::vector<Frac> faulhaberTraingle(int p) {
	std::vector<Frac> coeffs(p + 1);
 
	Frac q{ 1, p + 1 };
	int sign = -1;
	for (int j = 0; j <= p; j++) {
		sign *= -1;
		coeffs[p - j] = q * sign * binomial(p + 1, j) * bernoulli(j);
	}
 
	return coeffs;
}
 
int main() {
 
	for (int i = 0; i < 10; i++) {
		std::vector<Frac> coeffs = faulhaberTraingle(i);
		for (auto frac : coeffs) {
			std::cout << std::right << std::setw(5) << frac << "  ";
		}
		std::cout << std::endl;
	}
 
	return 0;
}
Task: Faulhaber's formula


C++: #include <iostream>
#include <numeric>
#include <sstream>
#include <vector>

class Frac {
public:
	Frac(long n, long d) {
		if (d == 0) {
			throw new std::runtime_error("d must not be zero");
		}

		long nn = n;
		long dd = d;
		if (nn == 0) {
			dd = 1;
		} else if (dd < 0) {
			nn = -nn;
			dd = -dd;
		}

		long g = abs(std::gcd(nn, dd));
		if (g > 1) {
			nn /= g;
			dd /= g;
		}

		num = nn;
		denom = dd;
	}

	Frac operator-() const {
		return Frac(-num, denom);
	}

	Frac operator+(const Frac& rhs) const {
		return Frac(num*rhs.denom + denom * rhs.num, rhs.denom*denom);
	}

	Frac operator-(const Frac& rhs) const {
		return Frac(num*rhs.denom - denom * rhs.num, rhs.denom*denom);
	}

	Frac operator*(const Frac& rhs) const {
		return Frac(num*rhs.num, denom*rhs.denom);
	}

	bool operator==(const Frac& rhs) const {
		return num == rhs.num && denom == rhs.denom;
	}

	bool operator!=(const Frac& rhs) const {
		return num != rhs.num || denom != rhs.denom;
	}

	bool operator<(const Frac& rhs) const {
		if (denom == rhs.denom) {
			return num < rhs.num;
		}
		return num * rhs.denom < rhs.num * denom;
	}

	friend std::ostream& operator<<(std::ostream&, const Frac&);

	static Frac ZERO() {
		return Frac(0, 1);
	}

	static Frac ONE() {
		return Frac(1, 1);
	}

private:
	long num;
	long denom;
};

std::ostream & operator<<(std::ostream & os, const Frac &f) {
	if (f.num == 0 || f.denom == 1) {
		return os << f.num;
	}

	std::stringstream ss;
	ss << f.num << "/" << f.denom;
	return os << ss.str();
}

Frac bernoulli(int n) {
	if (n < 0) {
		throw new std::runtime_error("n may not be negative or zero");
	}

	std::vector<Frac> a;
	for (int m = 0; m <= n; m++) {
		a.push_back(Frac(1, m + 1));
		for (int j = m; j >= 1; j--) {
			a[j - 1] = (a[j - 1] - a[j]) * Frac(j, 1);
		}
	}

	
	if (n != 1) return a[0];
	return -a[0];
}

int binomial(int n, int k) {
	if (n < 0 || k < 0 || n < k) {
		throw new std::runtime_error("parameters are invalid");
	}
	if (n == 0 || k == 0) return 1;

	int num = 1;
	for (int i = k + 1; i <= n; i++) {
		num *= i;
	}

	int denom = 1;
	for (int i = 2; i <= n - k; i++) {
		denom *= i;
	}

	return num / denom;
}

void faulhaber(int p) {
	using namespace std;
	cout << p << " : ";

	auto q = Frac(1, p + 1);
	int sign = -1;
	for (int j = 0; j < p + 1; j++) {
		sign *= -1;
		auto coeff = q * Frac(sign, 1) * Frac(binomial(p + 1, j), 1) * bernoulli(j);
		if (coeff == Frac::ZERO()) {
			continue;
		}
		if (j == 0) {
			if (coeff == -Frac::ONE()) {
				cout << "-";
			} else if (coeff != Frac::ONE()) {
				cout << coeff;
			}
		} else {
			if (coeff == Frac::ONE()) {
				cout << " + ";
			} else if (coeff == -Frac::ONE()) {
				cout << " - ";
			} else if (coeff < Frac::ZERO()) {
				cout << " - " << -coeff;
			} else {
				cout << " + " << coeff;
			}
		}
		int pwr = p + 1 - j;
		if (pwr > 1) {
			cout << "n^" << pwr;
		} else {
			cout << "n";
		}
	}
	cout << endl;
}

int main() {
	for (int i = 0; i < 10; i++) {
		faulhaber(i);
	}

	return 0;
}
Task: Prime conspiracy


C++: #include <vector>
#include <iostream>
#include <cmath>
#include <utility>
#include <map>
#include <iomanip>

bool isPrime( int i ) {
   int stop = std::sqrt( static_cast<double>( i ) ) ;
   for ( int d = 2 ; d <= stop ; d++ )
      if ( i % d == 0 )
	 return false ;
   return true ;
}

class Compare {
public :
   Compare( ) {
   }

   bool operator( ) ( const std::pair<int , int> & a , const std::pair<int, int> & b ) {
      if ( a.first != b.first ) 
	 return a.first < b.first ;
      else
	 return a.second < b.second ;
   }
};

int main( ) {
   std::vector<int> primes {2} ;
   int current = 3 ;
   while ( primes.size( ) < 1000000 ) {
      if ( isPrime( current ) ) 
	 primes.push_back( current ) ;
      current += 2 ;
   }
   Compare myComp ;
   std::map<std::pair<int, int>, int , Compare> conspiracy (myComp) ;
   for ( int i = 0 ; i < primes.size( ) -1 ; i++ ) {
      int a = primes[i] % 10 ;
      int b = primes[ i + 1 ] % 10 ;
      std::pair<int , int> numbers { a , b} ;
      conspiracy[numbers]++ ;
   }
   std::cout << "1000000 first primes. Transitions prime % 10 → next-prime % 10.\n" ;
   for ( auto it = conspiracy.begin( ) ; it != conspiracy.end( ) ; it++ ) {
      std::cout << (it->first).first << " -> " << (it->first).second << " count:" ;
      int frequency = it->second ;
      std::cout << std::right << std::setw( 15 ) << frequency << " frequency: " ;
      std::cout.setf(std::ios::fixed, std::ios::floatfield ) ;
      std::cout.precision( 2 ) ;
      std::cout << (static_cast<double>(frequency) / 1000000.0) * 100 << " %\n" ;
   }
   return 0 ;
}
Task: Elementary cellular automaton_Random number generator


C++: #include <bitset>
#include <stdio.h>

#define SIZE	           80
#define RULE               30
#define RULE_TEST(x)       (RULE & 1 << (7 & (x)))

void evolve(std::bitset<SIZE> &s) {
    int i;
    std::bitset<SIZE> t(0);
    t[SIZE-1] = RULE_TEST( s[0] << 2 | s[SIZE-1] << 1 | s[SIZE-2] );
    t[     0] = RULE_TEST( s[1] << 2 | s[     0] << 1 | s[SIZE-1] );
    for (i = 1; i < SIZE-1; i++)
	t[i] = RULE_TEST( s[i+1] << 2 | s[i] << 1 | s[i-1] );
    for (i = 0; i < SIZE; i++) s[i] = t[i];
}
void show(std::bitset<SIZE> s) {
    int i;
    for (i = SIZE; i--; ) printf("%c", s[i] ? '#' : ' ');
    printf("|\n");
}
unsigned char byte(std::bitset<SIZE> &s) {
    unsigned char b = 0;
    int i;
    for (i=8; i--; ) {
	b |= s[0] << i; 
	evolve(s);
    }
    return b;
}

int main() {
    int i;
    std::bitset<SIZE> state(1);
    for (i=10; i--; )
	printf("%u%c", byte(state), i ? ' ' : '\n');
    return 0;
}
Task: Statistics_Normal distribution


C++: #include <random>
#include <map>
#include <string>
#include <iostream>
#include <cmath>
#include <iomanip>

int main( ) {
   std::random_device myseed ;
   std::mt19937 engine ( myseed( ) ) ;
   std::normal_distribution<> normDistri ( 2 , 3 ) ;
   std::map<int , int> normalFreq ;
   int sum = 0 ; 
   double mean = 0.0 ;
   double stddev = 0.0 ;
   for ( int i = 1 ; i < 10001 ; i++ ) 
      ++normalFreq[ normDistri ( engine ) ] ;
   for ( auto MapIt : normalFreq ) {
      sum += MapIt.first * MapIt.second ;
   }
   mean = sum / 10000 ;
   stddev = sqrt( sum / 10000 ) ;
   std::cout << "The mean of the distribution is " << mean << " , the " ;
   std::cout << "standard deviation " << stddev << " !\n" ;
   std::cout << "And now the histogram:\n" ;
   for ( auto MapIt : normalFreq ) {
      std::cout << std::left << std::setw( 4 ) << MapIt.first << 
	 std::string( MapIt.second / 100 , '*' ) << std::endl ;
   }
   return 0 ;
}
Task: Minimum positive multiple in base 10 using only 0 and 1


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

__int128 imax(__int128 a, __int128 b) {
    if (a > b) {
        return a;
    }
    return b;
}

__int128 ipow(__int128 b, __int128 n) {
    if (n == 0) {
        return 1;
    }
    if (n == 1) {
        return b;
    }

    __int128 res = b;
    while (n > 1) {
        res *= b;
        n--;
    }
    return res;
}

__int128 imod(__int128 m, __int128 n) {
    __int128 result = m % n;
    if (result < 0) {
        result += n;
    }
    return result;
}

bool valid(__int128 n) {
    if (n < 0) {
        return false;
    }
    while (n > 0) {
        int r = n % 10;
        if (r > 1) {
            return false;
        }
        n /= 10;
    }
    return true;
}

__int128 mpm(const __int128 n) {
    if (n == 1) {
        return 1;
    }

    std::vector<__int128> L(n * n, 0);
    L[0] = 1;
    L[1] = 1;

    __int128 m, k, r, j;
    m = 0;
    while (true) {
        m++;
        if (L[(m - 1) * n + imod(-ipow(10, m), n)] == 1) {
            break;
        }
        L[m * n + 0] = 1;
        for (k = 1; k < n; k++) {
            L[m * n + k] = imax(L[(m - 1) * n + k], L[(m - 1) * n + imod(k - ipow(10, m), n)]);
        }
    }

    r = ipow(10, m);
    k = imod(-r, n);

    for (j = m - 1; j >= 1; j--) {
        if (L[(j - 1) * n + k] == 0) {
            r = r + ipow(10, j);
            k = imod(k - ipow(10, j), n);
        }
    }

    if (k == 1) {
        r++;
    }
    return r / n;
}

std::ostream& operator<<(std::ostream& os, __int128 n) {
    char buffer[64]; 
    int pos = (sizeof(buffer) / sizeof(char)) - 1;
    bool negative = false;

    if (n < 0) {
        negative = true;
        n = -n;
    }

    buffer[pos] = 0;
    while (n > 0) {
        int rem = n % 10;
        buffer[--pos] = rem + '0';
        n /= 10;
    }
    if (negative) {
        buffer[--pos] = '-';
    }
    return os << &buffer[pos];
}

void test(__int128 n) {
    __int128 mult = mpm(n);
    if (mult > 0) {
        std::cout << n << " * " << mult << " = " << (n * mult) << '\n';
    } else {
        std::cout << n << "(no solution)\n";
    }
}

int main() {
    int i;

    
    for (i = 1; i <= 10; i++) {
        test(i);
    }
    
    for (i = 95; i <= 105; i++) {
        test(i);
    }
    test(297);
    test(576);
    test(594); 
    test(891);
    test(909);
    test(999); 

    
    test(1998);
    test(2079);
    test(2251);
    test(2277);

    
    test(2439);
    test(2997);
    test(4878);

    return 0;
}
Task: Kosaraju


C++: #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);
    }
    while (it != end) {
        os << ", " << *it;
        it = std::next(it);
    }
    return os << "]";
}

std::vector<int> kosaraju(std::vector<std::vector<int>>& g) {
    
    auto size = g.size();
    std::vector<bool> vis(size);           
    std::vector<int> l(size);              
    auto x = size;                         
    std::vector<std::vector<int>> t(size); 

    
    std::function<void(int)> visit;
    visit = [&](int u) {
        if (!vis[u]) {
            vis[u] = true;
            for (auto v : g[u]) {
                visit(v);
                t[v].push_back(u); 
            }
            l[--x] = u;
        }
    };

    
    for (int i = 0; i < g.size(); ++i) {
        visit(i);
    }
    std::vector<int> c(size); 

    
    std::function<void(int, int)> assign;
    assign = [&](int u, int root) {
        if (vis[u]) { 
            vis[u] = false;
            c[u] = root;
            for (auto v : t[u]) {
                assign(v, root);
            }
        }
    };

    
    for (auto u : l) {
        assign(u, u);
    }

    return c;
}

std::vector<std::vector<int>> g = {
    {1},
    {2},
    {0},
    {1, 2, 4},
    {3, 5},
    {2, 6},
    {5},
    {4, 6, 7},
};

int main() {
    using namespace std;

    cout << kosaraju(g) << endl;

    return 0;
}
Task: SHA-256 Merkle tree


C++: #include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <vector>
#include <openssl/sha.h>

class sha256_exception : public std::exception {
public:
    const char* what() const noexcept override {
        return "SHA-256 error";
    }
};

class sha256 {
public:
    sha256() { reset(); }
    sha256(const sha256&) = delete;
    sha256& operator=(const sha256&) = delete;
    void reset() {
        if (SHA256_Init(&context_) == 0)
            throw sha256_exception();
    }
    void update(const void* data, size_t length) {
        if (SHA256_Update(&context_, data, length) == 0)
            throw sha256_exception();
    }
    std::vector<unsigned char> digest() {
        std::vector<unsigned char> digest(SHA256_DIGEST_LENGTH);
        if (SHA256_Final(digest.data(), &context_) == 0)
            throw sha256_exception();
        return digest;
    }
private:
    SHA256_CTX context_;
};

std::string digest_to_string(const std::vector<unsigned char>& digest) {
    std::ostringstream out;
    out << std::hex << std::setfill('0');
    for (size_t i = 0; i < digest.size(); ++i)
        out << std::setw(2) << static_cast<int>(digest[i]);
    return out.str();
}

std::vector<unsigned char> sha256_merkle_tree(std::istream& in, size_t block_size) {
    std::vector<std::vector<unsigned char>> hashes;
    std::vector<char> buffer(block_size);
    sha256 md;
    while (in) {
        in.read(buffer.data(), block_size);
        size_t bytes = in.gcount();
        if (bytes == 0)
            break;
        md.reset();
        md.update(buffer.data(), bytes);
        hashes.push_back(md.digest());
    }
    if (hashes.empty())
        return {};
    size_t length = hashes.size();
    while (length > 1) {
        size_t j = 0;
        for (size_t i = 0; i < length; i += 2, ++j) {
            auto& digest1 = hashes[i];
            auto& digest_out = hashes[j];
            if (i + 1 < length) {
                auto& digest2 = hashes[i + 1];
                md.reset();
                md.update(digest1.data(), digest1.size());
                md.update(digest2.data(), digest2.size());
                digest_out = md.digest();
            } else {
                digest_out = digest1;
            }
        }
        length = j;
    }
    return hashes[0];
}

int main(int argc, char** argv) {
    if (argc != 2) {
        std::cerr << "usage: " << argv[0] << " filename\n";
        return EXIT_FAILURE;
    }
    std::ifstream in(argv[1], std::ios::binary);
    if (!in) {
        std::cerr << "Cannot open file " << argv[1] << ".\n";
        return EXIT_FAILURE;
    }
    try {
        std::cout << digest_to_string(sha256_merkle_tree(in, 1024)) << '\n';
    } catch (const std::exception& ex) {
        std::cerr << ex.what() << "\n";
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}