WeixiangYan/CodeTransOcean huggingface dataset:
Task: Nonogram solver


C++: 

template<uint _N, uint _G> class Nonogram {
  enum class ng_val : char {X='#',B='.',V='?'};
  template<uint _NG> struct N {
    N() {}
    N(std::vector<int> ni,const int l) : X{},B{},Tx{},Tb{},ng(ni),En{},gNG(l){}
    std::bitset<_NG> X, B, T, Tx, Tb;
    std::vector<int> ng;
    int En, gNG;
    void        fn (const int n,const int i,const int g,const int e,const int l){ 
      if (fe(g,l,false) and fe(g+l,e,true)){
      if ((n+1) < ng.size()) {if (fe(g+e+l,1,false)) fn(n+1,i-e-1,g+e+l+1,ng[n+1],0);}
      else {
        if (fe(g+e+l,gNG-(g+e+l),false)){Tb &= T.flip(); Tx &= T.flip(); ++En;}
      }}
      if (l<=gNG-g-i-1) fn(n,i,g,e,l+1);
    }
    void        fi (const int n,const bool g) {X.set(n,g); B.set(n, not g);}
    ng_val      fg (const int n) const{return (X.test(n))? ng_val::X : (B.test(n))? ng_val::B : ng_val::V;}
    inline bool fe (const int n,const int i, const bool g){
      for (int e = n;e<n+i;++e) if ((g and fg(e)==ng_val::B) or (!g and fg(e)==ng_val::X)) return false; else T[e] = g;
      return true;
    }
    int         fl (){
      if (En == 1) return 1;
      Tx.set(); Tb.set(); En=0;
      fn(0,std::accumulate(ng.cbegin(),ng.cend(),0)+ng.size()-1,0,ng[0],0);
      return En;
    }}; 
  std::vector<N<_G>> ng;
  std::vector<N<_N>> gn;
  int En, zN, zG;
  void setCell(uint n, uint i, bool g){ng[n].fi(i,g); gn[i].fi(n,g);}
public:
  Nonogram(const std::vector<std::vector<int>>& n,const std::vector<std::vector<int>>& i,const std::vector<std::string>& g = {}) : ng{}, gn{}, En{}, zN(n.size()), zG(i.size()) {
    for (int n=0; n<zG; n++) gn.push_back(N<_N>(i[n],zN));
    for (int i=0; i<zN; i++) {
      ng.push_back(N<_G>(n[i],zG));
      if (i < g.size()) for(int e=0; e<zG or e<g[i].size(); e++) if (g[i][e]=='#') setCell(i,e,true);
    }}
  bool solve(){
    int i{}, g{};  
    for (int l = 0; l<zN; l++) {
      if ((g = ng[l].fl()) == 0) return false; else i+=g;
      for (int i = 0; i<zG; i++) if (ng[l].Tx[i] != ng[l].Tb[i]) setCell (l,i,ng[l].Tx[i]);
    }
    for (int l = 0; l<zG; l++) {
      if ((g = gn[l].fl()) == 0) return false; else i+=g;
      for (int i = 0; i<zN; i++) if (gn[l].Tx[i] != gn[l].Tb[i]) setCell (i,l,gn[l].Tx[i]);
    }
    if (i == En)    return false; else En = i;
    if (i == zN+zG) return true;  else return solve();
  }
  const std::string toStr() const {
    std::ostringstream n;
    for (int i = 0; i<zN; i++){for (int g = 0; g<zG; g++){n << static_cast<char>(ng[i].fg(g));}n<<std::endl;}
    return n.str();
  }};
Task: Integer long division


C++: #include <gmpxx.h>

#include <iomanip>
#include <iostream>
#include <map>
#include <string>

using big_int = mpz_class;

std::pair<std::string, size_t> divide(const big_int& n, const big_int& d) {
    assert(n >= 0);
    assert(d > 0);
    std::string result = big_int(n / d).get_str();
    result += '.';
    big_int c = 10 * (n % d);
    size_t digits = 0;
    std::map<big_int, size_t> seen;
    while (seen.count(c) == 0) {
        if (c == 0) {
            if (result.back() == '.')
                result.pop_back();
            return {result, 0};
        }
        seen[c] = digits++;
        if (c < d) {
            result += '0';
            c *= 10;
        } else {
            result += big_int(c / d).get_str();
            c = 10 * (c % d);
        }
    }
    return {result, digits - seen[c]};
}

int main() {
    big_int test[][2] = {
        {0, 1},   {1, 1},    {1, 5},
        {1, 3},   {1, 7},    {83, 60},
        {1, 17},  {10, 13},  {3227, 555},
        {1, 149}, {1, 5261}, {476837158203125, big_int("9223372036854775808")}};
    for (auto [n, d] : test) {
        auto [result, period] = divide(n, d);
        std::string str = n.get_str();
        str += '/';
        str += d.get_str();
        std::string repetend = result.substr(result.size() - period);
        if (repetend.size() > 30)
            repetend.replace(15, repetend.size() - 30, "...");
        result.resize(result.size() - period);
        std::cout << std::setw(35) << str << " = " << result;
        if (period != 0)
            std::cout << '{' << repetend << "} (period " << period << ')';
        std::cout << '\n';
    }
}
Task: Readline interface


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

std::vector<std::string> hist;

std::ostream& operator<<(std::ostream& os, const std::string& str) {
    return os << str.c_str();
}

void appendHistory(const std::string& name) {
    hist.push_back(name);
}

void hello() {
    std::cout << "Hello World!\n";
    appendHistory(__func__);
}

void history() {
    if (hist.size() == 0) {
        std::cout << "No history\n";
    } else {
        for (auto& str : hist) {
            std::cout << " - " << str << '\n';
        }
    }
    appendHistory(__func__);
}

void help() {
    std::cout << "Available commands:\n";
    std::cout << "  hello\n";
    std::cout << "  hist\n";
    std::cout << "  exit\n";
    std::cout << "  help\n";
    appendHistory(__func__);
}

int main() {
    bool done = false;
    std::string cmd;

    do {
        std::cout << "Enter a command, type help for a listing.\n";
        std::cin >> cmd;
        for (size_t i = 0; i < cmd.size(); ++i) {
            cmd[i] = toupper(cmd[i]);
        }

        if (strcmp(cmd.c_str(), "HELLO") == 0) {
            hello();
        } else if (strcmp(cmd.c_str(), "HIST") == 0) {
            history();
        } else if (strcmp(cmd.c_str(), "EXIT") == 0) {
            done = true;
        } else {
            help();
        }
    } while (!done);

    return 0;
}
Task: Ramanujan primes


C++: #include <chrono>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <vector>

class prime_counter {
public:
    explicit prime_counter(int limit);
    int prime_count(int n) const { return n < 1 ? 0 : count_.at(n); }

private:
    std::vector<int> count_;
};

prime_counter::prime_counter(int limit) : count_(limit, 1) {
    if (limit > 0)
        count_[0] = 0;
    if (limit > 1)
        count_[1] = 0;
    for (int i = 4; i < limit; i += 2)
        count_[i] = 0;
    for (int p = 3, sq = 9; sq < limit; p += 2) {
        if (count_[p]) {
            for (int q = sq; q < limit; q += p << 1)
                count_[q] = 0;
        }
        sq += (p + 1) << 2;
    }
    std::partial_sum(count_.begin(), count_.end(), count_.begin());
}

int ramanujan_max(int n) {
    return static_cast<int>(std::ceil(4 * n * std::log(4 * n)));
}

int ramanujan_prime(const prime_counter& pc, int n) {
    int max = ramanujan_max(n);
    for (int i = max; i >= 0; --i) {
        if (pc.prime_count(i) - pc.prime_count(i / 2) < n)
            return i + 1;
    }
    return 0;
}

int main() {
    std::cout.imbue(std::locale(""));
    auto start = std::chrono::high_resolution_clock::now();
    prime_counter pc(1 + ramanujan_max(100000));
    for (int i = 1; i <= 100; ++i) {
        std::cout << std::setw(5) << ramanujan_prime(pc, i)
                  << (i % 10 == 0 ? '\n' : ' ');
    }
    std::cout << '\n';
    for (int n = 1000; n <= 100000; n *= 10) {
        std::cout << "The " << n << "th Ramanujan prime is " << ramanujan_prime(pc, n)
              << ".\n";
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "\nElapsed time: "
              << std::chrono::duration<double>(end - start).count() * 1000
              << " milliseconds\n";
}
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';
    }
}
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;
}
Task: Tree datastructures


C++: #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(const std::string& name) {
        children_.emplace_back(name);
        return children_.back();
    }
    void print(std::ostream& out) const {
        print(out, 0);
    }
    const std::string& name() const {
        return name_;
    }
    const std::list<nest_tree>& children() const {
        return children_;
    }
    bool equals(const nest_tree& n) const {
        return name_ == n.name_ && children_ == n.children_;
    }
private:
    void print(std::ostream& out, int level) const {
        std::string indent(level * 4, ' ');
        out << indent << name_ << '\n';
        for (const nest_tree& child : children_)
            child.print(out, level + 1);
    }
    std::string name_;
    std::list<nest_tree> children_;
};

bool operator==(const nest_tree& a, const nest_tree& b) {
    return a.equals(b);
}

class indent_tree {
public:
    explicit indent_tree(const nest_tree& n) {
        items_.emplace_back(0, n.name());
        from_nest(n, 0);
    }
    void print(std::ostream& out) const {
        for (const auto& item : items_)
            std::cout << item.first << ' ' << item.second << '\n';
    }
    nest_tree to_nest() const {
        nest_tree n(items_[0].second);
        to_nest_(n, 1, 0);
        return n;
    }
private:
    void from_nest(const nest_tree& n, int level) {
        for (const nest_tree& child : n.children()) {
            items_.emplace_back(level + 1, child.name());
            from_nest(child, level + 1);
        }
    }
    size_t to_nest_(nest_tree& n, size_t pos, int level) const {
        while (pos < items_.size() && items_[pos].first == level + 1) {
            nest_tree& child = n.add_child(items_[pos].second);
            pos = to_nest_(child, pos + 1, level + 1);
        }
        return pos;
    }
    std::vector<std::pair<int, std::string>> items_;
};

int main() {
    nest_tree n("RosettaCode");
    auto& child1 = n.add_child("rocks");
    auto& child2 = n.add_child("mocks");
    child1.add_child("code");
    child1.add_child("comparison");
    child1.add_child("wiki");
    child2.add_child("trolling");
    
    std::cout << "Initial nest format:\n";
    n.print(std::cout);
    
    indent_tree i(n);
    std::cout << "\nIndent format:\n";
    i.print(std::cout);
    
    nest_tree n2(i.to_nest());
    std::cout << "\nFinal nest format:\n";
    n2.print(std::cout);

    std::cout << "\nAre initial and final nest formats equal? "
        << std::boolalpha << n.equals(n2) << '\n';
    
    return 0;
}
Task: Powerful numbers


C++: #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 (auto p : primes) {
        auto p2 = p * p;
        if (p2 > n)
            break;
        if (n % p2 == 0)
            return false;
    }
    return true;
}

uint64_t iroot(uint64_t n, uint64_t r) {
    
    static constexpr double adj = 1e-6;
    return static_cast<uint64_t>(std::pow(n, 1.0/r) + adj);
}

uint64_t ipow(uint64_t n, uint64_t p) {
    uint64_t prod = 1;
    for (; p > 0; p >>= 1) {
        if (p & 1)
            prod *= n;
        n *= n;
    }
    return prod;
}

std::vector<uint64_t> powerful(uint64_t n, uint64_t k) {
    std::vector<uint64_t> result;
    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
        if (r < k) {
            result.push_back(m);
            return;
        }
        uint64_t root = iroot(n/m, r);
        for (uint64_t v = 1; v <= root; ++v) {
            if (r > k && (!is_square_free(v) || std::gcd(m, v) != 1))
                continue;
            f(m * ipow(v, r), r - 1);
        }
    };
    f(1, 2*k - 1);
    std::sort(result.begin(), result.end());
    return result;
}

uint64_t powerful_count(uint64_t n, uint64_t k) {
    uint64_t count = 0;
    std::function<void(uint64_t, uint64_t)> f = [&](uint64_t m, uint64_t r) {
        if (r <= k) {
            count += iroot(n/m, r);
            return;
        }
        uint64_t root = iroot(n/m, r);
        for (uint64_t v = 1; v <= root; ++v) {
            if (is_square_free(v) && std::gcd(m, v) == 1)
                f(m * ipow(v, r), r - 1);
        }
    };
    f(1, 2*k - 1);
    return count;
}

int main() {
    const size_t max = 5;
    for (uint64_t k = 2, p = 100; k <= 10; ++k, p *= 10) {
        auto result = powerful(p, k);
        std::cout << result.size() << " " << k
            << "-powerful numbers <= 10^" << k << ":";
        for (size_t i = 0; i < result.size(); ++i) {
            if (i == max)
                std::cout << " ...";
            else if (i < max || i + max >= result.size())
                std::cout << ' ' << result[i];
        }
        std::cout << '\n';
    }
    std::cout << '\n';
    for (uint64_t k = 2; k <= 10; ++k) {
        std::cout << "Count of " << k << "-powerful numbers <= 10^j for 0 <= j < "
            << k + 10 << ":";
        for (uint64_t j = 0, p = 1; j < k + 10; ++j, p *= 10)
            std::cout << ' ' << powerful_count(p, k);
        std::cout << '\n';
    }
}
Task: Execute CopyPasta Language


C++: #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& str, const string& chars = "\t\n\v\f\r ")
{
	str.erase(0, str.find_first_not_of(chars));
	return str;
}
string& rtrim(string& str, const string& chars = "\t\n\v\f\r ")
{
	str.erase(str.find_last_not_of(chars) + 1);
	return str;
}
string& trim(string& str, const string& chars = "\t\n\v\f\r ")
{
	return ltrim(rtrim(str, chars), chars);
}

int main(int argc, char *argv[])
{
	
	string fname = "";
	string source = "";
	try
	{
		fname = argv[1];
		ifstream t(fname);

		t.seekg(0, ios::end);
		source.reserve(t.tellg());
		t.seekg(0, ios::beg);

		source.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
	}
	catch(const exception& e)
	{
		fatal_error("error while trying to read from specified file", argv);
	}

	
	string clipboard = "";

	
	int loc = 0;
	string remaining = source;
	string line = "";
	string command = "";
	stringstream ss;
	while(remaining.find("\n") != string::npos)
	{
		
		line = remaining.substr(0, remaining.find("\n"));
		command = trim(line);
		remaining = remaining.substr(remaining.find("\n") + 1);
		
		try
		{
			if(line == "Copy")
			{
				line = remaining.substr(0, remaining.find("\n"));
				remaining = remaining.substr(remaining.find("\n") + 1);
				clipboard += line;
			}
			else if(line == "CopyFile")
			{
				line = remaining.substr(0, remaining.find("\n"));
				remaining = remaining.substr(remaining.find("\n") + 1);
				if(line == "TheF*ckingCode")
					clipboard += source;
				else
				{
					string filetext = "";
					ifstream t(line);

					t.seekg(0, ios::end);
					filetext.reserve(t.tellg());
					t.seekg(0, ios::beg);

					filetext.assign((istreambuf_iterator<char>(t)), istreambuf_iterator<char>());
					clipboard += filetext;
				}
			}
			else if(line == "Duplicate")
			{
				line = remaining.substr(0, remaining.find("\n"));
				remaining = remaining.substr(remaining.find("\n") + 1);
				int amount = stoi(line);
				string origClipboard = clipboard;
				for(int i = 0; i < amount - 1; i++) {
					clipboard += origClipboard;
				}
			}
			else if(line == "Pasta!")
			{
				cout << clipboard << endl;
				return 0;
			}
			else
			{
				ss << (loc + 1);
				fatal_error("unknown command '" + command + "' encounter on line " + ss.str(), argv);
			}
		}
		catch(const exception& e)
		{
			ss << (loc + 1);
			fatal_error("error while executing command '" + command + "' on line " + ss.str(), argv);
		}

		
		loc += 2;
	}

	
	return 0;
}
Task: Decision tables







Python: 

def dt_creator():
    print("\n\nCREATING THE DECISION TABLE\n")
    conditions = input("Input conditions, in order, separated by commas: ")
    conditions = [c.strip() for c in conditions.split(',')]
    print( ("\nThat was %s conditions:\n  " % len(conditions))
           + '\n  '.join("%i: %s" % x for x in enumerate(conditions, 1)) )
    print("\nInput an action, a semicolon, then a list of tuples of rules that trigger it. End with a blank line")
    action2rules, action = [], ' '
    while action:
        action = input("%i: " % (len(action2rules) + 1)).strip()
        if action:
            name, _, rules = [x.strip() for x in action.partition(';')]
            rules = eval(rules)
            assert all(len(rule) == len(conditions) for rule in rules), \
                   "The number of conditions in a rule to trigger this action is wrong" 
            action2rules.append((name, rules))
    actions = [x[0] for x in action2rules]
    
    rule2actions = dict((y,[]) for y in set(sum((x[1] for x in action2rules), [])))
    for action, rules in action2rules:
        for r in rules:
            rule2actions[r].append( action )
    return conditions, rule2actions

def dt_user(dt, default=['Pray!']):
    conditions, rule2actions = dt
    print("\n\nUSING THE DECISION TABLE\n")
    rule = tuple(int('y' == input("%s? (Answer y if statement is true or n): " % c)) for c in conditions)
    print("Try this:\n  " + '\n  '.join(rule2actions.get(rule, default)))

if __name__ == '__main__':
    dt = dt_creator()
    dt_user(dt)
    dt_user(dt)
    dt_user(dt)
Task: Draw a pixel







Python: from PIL import Image

img = Image.new('RGB', (320, 240))
pixels = img.load()
pixels[100,100] = (255,0,0)
img.show()
Task: Verify distribution uniformity_Naive







Python: from collections import Counter
from pprint import pprint as pp

def distcheck(fn, repeats, delta):
    
    bin = Counter(fn() for i in range(repeats))
    target = repeats // len(bin)
    deltacount = int(delta / 100. * target)
    assert all( abs(target - count) < deltacount
                for count in bin.values() ), "Bin distribution skewed from %i +/- %i: %s" % (
                    target, deltacount, [ (key, target - count)
                                          for key, count in sorted(bin.items()) ]
                    )
    pp(dict(bin))
Task: Colour bars_Display







Python: 


from livewires import *

horiz=640; vert=480
begin_graphics(width=horiz,height=vert,title="v_stripes",background=Colour.black)
NameColors=["black","red","green","dark_blue","purple","blue","yellow","white"]
stepik=horiz/len(NameColors)

for index,each in enumerate(NameColors):
	ExcStrng="set_colour(Colour."+each+")"
	exec ExcStrng
	box(index*stepik,0,(index+1)*stepik,vert,filled=1)

while keys_pressed() != ['x']: 
	pass

end_graphics()
Task: Dining philosophers







Python: import threading
import random
import time










class Philosopher(threading.Thread):
    
    running = True

    def __init__(self, xname, forkOnLeft, forkOnRight):
        threading.Thread.__init__(self)
        self.name = xname
        self.forkOnLeft = forkOnLeft
        self.forkOnRight = forkOnRight

    def run(self):
        while(self.running):
            
            time.sleep( random.uniform(3,13))
            print '%s is hungry.' % self.name
            self.dine()

    def dine(self):
        fork1, fork2 = self.forkOnLeft, self.forkOnRight

        while self.running:
            fork1.acquire(True)
            locked = fork2.acquire(False)
            if locked: break
            fork1.release()
            print '%s swaps forks' % self.name
            fork1, fork2 = fork2, fork1
        else:
            return

        self.dining()
        fork2.release()
        fork1.release()

    def dining(self):			
        print '%s starts eating '% self.name
        time.sleep(random.uniform(1,10))
        print '%s finishes eating and leaves to think.' % self.name

def DiningPhilosophers():
    forks = [threading.Lock() for n in range(5)]
    philosopherNames = ('Aristotle','Kant','Spinoza','Marx', 'Russel')

    philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
            for i in range(5)]

    random.seed(507129)
    Philosopher.running = True
    for p in philosophers: p.start()
    time.sleep(100)
    Philosopher.running = False
    print ("Now we're finishing.")

DiningPhilosophers()
Task: Exceptions







Python: import exceptions
class SillyError(exceptions.Exception):
    def __init__(self,args=None):
         self.args=args
Task: Keyboard input_Flush the keyboard buffer







Python: def flush_input():
    try:
        import msvcrt
        while msvcrt.kbhit():
            msvcrt.getch()
    except ImportError:
        import sys, termios
        termios.tcflush(sys.stdin, termios.TCIOFLUSH)
Task: Numeric error propagation


C++: #pragma once

#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>

class Approx {
public:
    Approx(double _v, double _s = 0.0) : v(_v), s(_s) {}

    operator std::string() const {
        std::ostringstream os("");
        os << std::setprecision(15) << v << " ±" << std::setprecision(15) << s << std::ends;
        return os.str();
    }

    Approx operator +(const Approx& a) const { return Approx(v + a.v, sqrt(s * s + a.s * a.s)); }
    Approx operator +(double d) const { return Approx(v + d, s); }
    Approx operator -(const Approx& a) const { return Approx(v - a.v, sqrt(s * s + a.s * a.s)); }
    Approx operator -(double d) const { return Approx(v - d, s); }

    Approx operator *(const Approx& a) const {
        const double t = v * a.v;
        return Approx(v, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));
    }

    Approx operator *(double d) const { return Approx(v * d, fabs(d * s)); }

    Approx operator /(const Approx& a) const {
        const double t = v / a.v;
        return Approx(t, sqrt(t * t * s * s / (v * v) + a.s * a.s / (a.v * a.v)));
    }

    Approx operator /(double d) const { return Approx(v / d, fabs(d * s)); }

    Approx pow(double d) const {
        const double t = ::pow(v, d);
        return Approx(t, fabs(t * d * s / v));
    }

private:
    double v, s;
};