WeixiangYan/CodeTransOcean huggingface dataset:
Task: Even numbers which cannot be expressed as the sum of two twin primes


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

std::vector<bool> prime_sieve(int limit) {
    std::vector<bool> sieve(limit, true);
    if (limit > 0)
        sieve[0] = false;
    if (limit > 1)
        sieve[1] = false;
    for (int i = 4; i < limit; i += 2)
        sieve[i] = false;
    for (int p = 3, sq = 9; sq < limit; p += 2) {
        if (sieve[p]) {
            for (int q = sq; q < limit; q += p << 1)
                sieve[q] = false;
        }
        sq += (p + 1) << 2;
    }
    return sieve;
}

void print_non_twin_prime_sums(const std::vector<bool>& sums) {
    int count = 0;
    for (size_t i = 2; i < sums.size(); i += 2) {
        if (!sums[i]) {
            ++count;
            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\nFound " << count << '\n';
}

int main() {
    const int limit = 100001;

    std::vector<bool> sieve = prime_sieve(limit + 2);
    
    for (size_t i = 0; i < limit; ++i) {
        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
            sieve[i] = false;
    }

    std::vector<bool> twin_prime_sums(limit, false);
    for (size_t i = 0; i < limit; ++i) {
        if (sieve[i]) {
            for (size_t j = i; i + j < limit; ++j) {
                if (sieve[j])
                    twin_prime_sums[i + j] = true;
            }
        }
    }

    std::cout << "Non twin prime sums:\n";
    print_non_twin_prime_sums(twin_prime_sums);

    sieve[1] = true;
    for (size_t i = 1; i + 1 < limit; ++i) {
        if (sieve[i])
            twin_prime_sums[i + 1] = true;
    }

    std::cout << "\nNon twin prime sums (including 1):\n";
    print_non_twin_prime_sums(twin_prime_sums);
}






Python: 

from sympy import sieve


def nonpairsums(include1=False, limit=20_000):
    
    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)
            for i in range(limit+2)]
    if include1:
        tpri[1] = True
    twinsums = [False] * (limit * 2)
    for i in range(limit):
        for j in range(limit-i+1):
            if tpri[i] and tpri[j]:
                twinsums[i + j] = True

    return [i for i in range(2, limit+1, 2) if not twinsums[i]]


print('Non twin prime sums:')
for k, p in enumerate(nonpairsums()):
    print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')

print('\n\nNon twin prime sums (including 1):')
for k, p in enumerate(nonpairsums(include1=True)):
    print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
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;
}






Python: def kosaraju(g):
    class nonlocal: pass

    
    size = len(g)

    vis = [False]*size 
    l = [0]*size
    nonlocal.x = size
    t = [[]]*size   

    def visit(u):
        if not vis[u]:
            vis[u] = True
            for v in g[u]:
                visit(v)
                t[v] = t[v] + [u]
            nonlocal.x = nonlocal.x - 1
            l[nonlocal.x] = u

    
    for u in range(len(g)):
        visit(u)
    c = [0]*size

    def assign(u, root):
        if vis[u]:
            vis[u] = False
            c[u] = root
            for v in t[u]:
                assign(v, root)

    
    for u in l:
        assign(u, u)

    return c

g = [[1], [2], [0], [1,2,4], [3,5], [2,6], [5], [4,6,7]]
print kosaraju(g)
Task: Variables


C++: int a;






Python: 
example1 = 3
example2 = 3.0
example3 = True
example4 = "hello"


example1 = "goodbye"
Task: Monads_Writer monad


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

using namespace std;


struct LoggingMonad
{
    double Value;
    string Log;
};


auto operator>>(const LoggingMonad& monad, auto f)
{
    auto result = f(monad.Value);
    return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}


auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };


auto MakeWriter = [](auto f, string message)
{
    return [=](double x){return LoggingMonad(f(x), message);};
};


auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");


int main()
{
    
    auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
    cout << result.Log << "\nResult: " << result.Value;
}






Python: 
from __future__ import annotations

import functools
import math
import os

from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union


T = TypeVar("T")


class Writer(Generic[T]):
    def __init__(self, value: Union[T, Writer[T]], *msgs: str):
        if isinstance(value, Writer):
            self.value: T = value.value
            self.msgs: List[str] = value.msgs + list(msgs)
        else:
            self.value = value
            self.msgs = list(f"{msg}: {self.value}" for msg in msgs)

    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        writer = func(self.value)
        return Writer(writer, *self.msgs)

    def __rshift__(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        return self.bind(func)

    def __str__(self):
        return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"

    def __repr__(self):
        return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"


def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
    

    @functools.wraps(func)
    def wrapped(value):
        return Writer(func(value), msg)

    return wrapped


if __name__ == "__main__":
    square_root = lift(math.sqrt, "square root")
    add_one = lift(lambda x: x + 1, "add one")
    half = lift(lambda x: x / 2, "div two")

    print(Writer(5, "initial") >> square_root >> add_one >> half)
Task: Honaker primes


C++: #include <iomanip>
#include <iostream>
#include <sstream>
#include <utility>

#include <primesieve.hpp>

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

class honaker_prime_generator {
public:
    std::pair<uint64_t, uint64_t> next();

private:
    primesieve::iterator pi_;
    uint64_t index_ = 0;
};

std::pair<uint64_t, uint64_t> honaker_prime_generator::next() {
    for (;;) {
        uint64_t prime = pi_.next_prime();
        ++index_;
        if (digit_sum(index_) == digit_sum(prime))
            return std::make_pair(index_, prime);
    }
}

std::ostream& operator<<(std::ostream& os,
                         const std::pair<uint64_t, uint64_t>& p) {
    std::ostringstream str;
    str << '(' << p.first << ", " << p.second << ')';
    return os << str.str();
}

int main() {
    honaker_prime_generator hpg;
    std::cout << "First 50 Honaker primes (index, prime):\n";
    int i = 1;
    for (; i <= 50; ++i)
        std::cout << std::setw(11) << hpg.next() << (i % 5 == 0 ? '\n' : ' ');
    for (; i < 10000; ++i)
        hpg.next();
    std::cout << "\nTen thousandth: " << hpg.next() << '\n';
}






Python: 


from pyprimesieve import primes


def digitsum(num):
    
    return sum(int(c) for c in str(num))


def generate_honaker(limit=5_000_000):
    
    honaker = [(i + 1, p) for i, p in enumerate(primes(limit)) if digitsum(p) == digitsum(i + 1)]
    for hcount, (ppi, pri) in enumerate(honaker):
        yield hcount + 1, ppi, pri


print('First 50 Honaker primes:')
for p in generate_honaker():
    if p[0] < 51:
        print(f'{str(p):16}', end='\n' if p[0] % 5 == 0 else '')
    elif p[0] == 10_000:
        print(f'\nThe 10,000th Honaker prime is the {p[1]:,}th one, which is {p[2]:,}.')
        break
Task: De Polignac numbers


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

bool is_prime(int n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (int p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

bool is_depolignac_number(int n) {
    for (int p = 1; p < n; p <<= 1) {
        if (is_prime(n - p))
            return false;
    }
    return true;
}

int main() {
    std::cout.imbue(std::locale(""));
    std::cout << "First 50 de Polignac numbers:\n";
    for (int n = 1, count = 0; count < 10000; n += 2) {
        if (is_depolignac_number(n)) {
            ++count;
            if (count <= 50)
                std::cout << std::setw(5) << n
                          << (count % 10 == 0 ? '\n' : ' ');
            else if (count == 1000)
                std::cout << "\nOne thousandth: " << n << '\n';
            else if (count == 10000)
                std::cout << "\nTen thousandth: " << n << '\n';
        }
    }
}






Python: 

from sympy import isprime
from math import log
from numpy import ndarray

max_value = 1_000_000

all_primes = [i for i in range(max_value + 1) if isprime(i)]
powers_of_2 = [2**i for i in range(int(log(max_value, 2)))]

allvalues = ndarray(max_value, dtype=bool)
allvalues[:] = True

for i in all_primes:
    for j in powers_of_2:
        if i + j < max_value:
            allvalues[i + j] = False
        
dePolignac = [n for n in range(1, max_value) if n & 1 == 1 and allvalues[n]]

print('First fifty de Polignac numbers:')
for i, n in enumerate(dePolignac[:50]):
    print(f'{n:5}', end='\n' if (i + 1) % 10 == 0 else '')
    
print(f'\nOne thousandth: {dePolignac[999]:,}')
print(f'\nTen thousandth: {dePolignac[9999]:,}')
Task: Zsigmondy numbers


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

std::vector<uint64_t> divisors(uint64_t n) {
    std::vector<uint64_t> result{1};
    uint64_t power = 2;
    for (; (n & 1) == 0; power <<= 1, n >>= 1)
        result.push_back(power);
    for (uint64_t p = 3; p * p <= n; p += 2) {
        size_t size = result.size();
        for (power = p; n % p == 0; power *= p, n /= p)
            for (size_t i = 0; i != size; ++i)
                result.push_back(power * result[i]);
    }
    if (n > 1) {
        size_t size = result.size();
        for (size_t i = 0; i != size; ++i)
            result.push_back(n * result[i]);
    }
    sort(result.begin(), result.end());
    return result;
}

uint64_t ipow(uint64_t base, uint64_t exp) {
    if (exp == 0)
        return 1;
    if ((exp & 1) == 0)
        return ipow(base * base, exp >> 1);
    return base * ipow(base * base, (exp - 1) >> 1);
}

uint64_t zsigmondy(uint64_t n, uint64_t a, uint64_t b) {
    auto p = ipow(a, n) - ipow(b, n);
    auto d = divisors(p);
    if (d.size() == 2)
        return p;
    std::vector<uint64_t> dms(n - 1);
    for (uint64_t m = 1; m < n; ++m)
        dms[m - 1] = ipow(a, m) - ipow(b, m);
    for (auto i = d.rbegin(); i != d.rend(); ++i) {
        uint64_t z = *i;
        if (all_of(dms.begin(), dms.end(),
                   [z](uint64_t x) { return std::gcd(x, z) == 1; }))
            return z;
    }
    return 1;
}

void test(uint64_t a, uint64_t b) {
    std::cout << "Zsigmondy(n, " << a << ", " << b << "):\n";
    for (uint64_t n = 1; n <= 20; ++n) {
        std::cout << zsigmondy(n, a, b) << ' ';
    }
    std::cout << "\n\n";
}

int main() {
    test(2, 1);
    test(3, 1);
    test(4, 1);
    test(5, 1);
    test(6, 1);
    test(7, 1);
    test(3, 2);
    test(5, 3);
    test(7, 3);
    test(7, 5);
}






Python: 

from math import gcd
from sympy import divisors


def zsig(num, aint, bint):
    
    assert aint > bint
    dexpms = [aint**i - bint**i for i in range(1, num)]
    dexpn = aint**num - bint**num
    return max([d for d in divisors(dexpn) if all(gcd(k, d) == 1 for k in dexpms)])


tests = [(2, 1), (3, 1), (4, 1), (5, 1), (6, 1),
         (7, 1), (3, 2), (5, 3), (7, 3), (7, 5)]
for (a, b) in tests:
    print(f'\nZsigmondy(n, {a}, {b}):', ', '.join(
        [str(zsig(n, a, b)) for n in range(1, 21)]))
Task: Average loop length

C: #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define MAX_N 20
#define TIMES 1000000

double factorial(int n) {
	double f = 1;
	int i;
	for (i = 1; i <= n; i++) f *= i;
	return f;
}

double expected(int n) {
	double sum = 0;
	int i;
	for (i = 1; i <= n; i++)
		sum += factorial(n) / pow(n, i) / factorial(n - i);
	return sum;
}

int randint(int n) {
	int r, rmax = RAND_MAX / n * n;
	while ((r = rand()) >= rmax);
	return r / (RAND_MAX / n);
}

int test(int n, int times) {
	int i, count = 0;
	for (i = 0; i < times; i++) {
		int x = 1, bits = 0;
		while (!(bits & x)) {
			count++;
			bits |= x;
			x = 1 << randint(n);
		}
	}
	return count;
}

int main(void) {
	srand(time(0));
	puts(" n\tavg\texp.\tdiff\n-------------------------------");

	int n;
	for (n = 1; n <= MAX_N; n++) {
		int cnt = test(n, TIMES);
		double avg = (double)cnt / TIMES;
		double theory = expected(n);
		double diff = (avg / theory - 1) * 100;
		printf("%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff);
	}
	return 0;
}



C#: public class AverageLoopLength {
	private static int N = 100000;
	
	private static double analytical(int n) {
		double[] factorial = new double[n + 1];
		double[] powers = new double[n + 1];
		powers[0] = 1.0;
		factorial[0] = 1.0;
		for (int i = 1; i <= n; i++) {
			factorial[i] = factorial[i - 1] * i;
			powers[i] = powers[i - 1] * n;
		}
		double sum = 0;
		
		for (int i = 1; i <= n; i++) {
			sum += factorial[n] / factorial[n - i] / powers[i];
		}
		return sum;
	}

	private static double average(int n) {
		Random rnd = new Random();
		double sum = 0.0;
		for (int a = 0; a < N; a++) {
			int[] random = new int[n];
			for (int i = 0; i < n; i++) {
				random[i] = rnd.Next(n);
			}
			var seen = new HashSet<double>(n);
			int current = 0;
			int length = 0;
			while (seen.Add(current)) {
				length++;
				current = random[current];
			}
			sum += length;
		}
		return sum / N;
	}
	
	public static void Main(string[] args) {
	Console.WriteLine(" N    average    analytical    (error)");
	Console.WriteLine("===  =========  ============  =========");
		for (int i = 1; i <= 20; i++) {
			var average = AverageLoopLength.average(i);
			var analytical = AverageLoopLength.analytical(i);
			Console.WriteLine("{0,3} {1,10:N4} {2,13:N4}  {3,8:N2}%", i, average, analytical, (analytical - average) / analytical * 100);
		}
	}
}
Task: String interpolation (included)

C: #include <stdio.h>

int main() {
  const char *extra = "little";
  printf("Mary had a %s lamb.\n", extra);
  return 0;
}



C#: class Program
{
    static void Main()
    {
        string extra = "little";
        string formatted = $"Mary had a {extra} lamb.";
        System.Console.WriteLine(formatted);
    }
}
Task: Partition function P

C: #include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <gmp.h>

mpz_t* partition(uint64_t n) {
	mpz_t *pn = (mpz_t *)malloc((n + 2) * sizeof(mpz_t));
	mpz_init_set_ui(pn[0], 1);
	mpz_init_set_ui(pn[1], 1);
	for (uint64_t i = 2; i < n + 2; i ++) {
		mpz_init(pn[i]);
		for (uint64_t k = 1, penta; ; k++) {
			penta = k * (3 * k - 1) >> 1;
			if (penta >= i) break;
			if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
			else mpz_sub(pn[i], pn[i], pn[i - penta]);
			penta += k;
			if (penta >= i) break;
			if (k & 1) mpz_add(pn[i], pn[i], pn[i - penta]);
			else mpz_sub(pn[i], pn[i], pn[i - penta]);
		}
	}
	mpz_t *tmp = &pn[n + 1];
	for (uint64_t i = 0; i < n + 1; i ++) mpz_clear(pn[i]);
	free(pn);
	return tmp;
}

int main(int argc, char const *argv[]) {
	clock_t start = clock();
	mpz_t *p = partition(6666);
	gmp_printf("%Zd\n", p);
	printf("Elapsed time: %.04f seconds\n",
		(double)(clock() - start) / (double)CLOCKS_PER_SEC);
	return 0;
}



C#: using System;

class Program {

    const long Lm = (long)1e18;
    const string Fm = "D18";

    
    struct LI { public long lo, ml, mh, hi, tp; }

    static void inc(ref LI d, LI s) { 
        if ((d.lo += s.lo) >= Lm) { d.ml++; d.lo -= Lm; }
        if ((d.ml += s.ml) >= Lm) { d.mh++; d.ml -= Lm; }
        if ((d.mh += s.mh) >= Lm) { d.hi++; d.mh -= Lm; }
        if ((d.hi += s.hi) >= Lm) { d.tp++; d.hi -= Lm; }
        d.tp += s.tp;
    }
 
    static void dec(ref LI d, LI s) { 
        if ((d.lo -= s.lo) < 0) { d.ml--; d.lo += Lm; }
        if ((d.ml -= s.ml) < 0) { d.mh--; d.ml += Lm; }
        if ((d.mh -= s.mh) < 0) { d.hi--; d.mh += Lm; }
        if ((d.hi -= s.hi) < 0) { d.tp--; d.hi += Lm; }
        d.tp -= s.tp;
    }

    static LI set(long s) { LI d;
      d.lo = s; d.ml = d.mh = d.hi = d.tp = 0; return d; }

  static string fmt(LI x) { 
    if (x.tp > 0) return x.tp.ToString() + x.hi.ToString(Fm) + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.hi > 0) return x.hi.ToString() + x.mh.ToString(Fm) + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.mh > 0) return x.mh.ToString() + x.ml.ToString(Fm) + x.lo.ToString(Fm);
    if (x.ml > 0) return x.ml.ToString() + x.lo.ToString(Fm);
    return x.lo.ToString();
  }

  static LI partcount(int n) {
    var P = new LI[n + 1]; P[0] = set(1);
    for (int i = 1; i <= n; i++) {
      int k = 0, d = -2, j = i;
      LI x = set(0);
      while (true) {
        if ((j -= (d += 3) -k) >= 0) inc(ref x, P[j]); else break;
        if ((j -= ++k)         >= 0) inc(ref x, P[j]); else break;
        if ((j -= (d += 3) -k) >= 0) dec(ref x, P[j]); else break;
        if ((j -= ++k)         >= 0) dec(ref x, P[j]); else break;
      }
      P[i] = x;
    }
    return P[n];
  }

  static void Main(string[] args) {
    var sw = System.Diagnostics.Stopwatch.StartNew ();
    var res = partcount(6666); sw.Stop();
    Console.Write("{0}  {1} ms", fmt(res), sw.Elapsed.TotalMilliseconds);
  }
}
Task: Numbers with prime digits whose sum is 13

C: #include <stdbool.h>
#include <stdio.h>

bool primeDigitsSum13(int n) {
    int sum = 0;
    while (n > 0) {
        int r = n % 10;
        switch (r) {
        case 2:
        case 3:
        case 5:
        case 7:
            break;
        default:
            return false;
        }
        n /= 10;
        sum += r;
    }
    return sum == 13;
}

int main() {
    int i, c;

    
    c = 0;
    for (i = 1; i < 1000000; i++) {
        if (primeDigitsSum13(i)) {
            printf("%6d ", i);
            if (c++ == 10) {
                c = 0;
                printf("\n");
            }
        }
    }
    printf("\n");

    return 0;
}



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: Numbers with prime digits whose sum is 13

C: #include <stdbool.h>
#include <stdio.h>

bool primeDigitsSum13(int n) {
    int sum = 0;
    while (n > 0) {
        int r = n % 10;
        switch (r) {
        case 2:
        case 3:
        case 5:
        case 7:
            break;
        default:
            return false;
        }
        n /= 10;
        sum += r;
    }
    return sum == 13;
}

int main() {
    int i, c;

    
    c = 0;
    for (i = 1; i < 1000000; i++) {
        if (primeDigitsSum13(i)) {
            printf("%6d ", i);
            if (c++ == 10) {
                c = 0;
                printf("\n");
            }
        }
    }
    printf("\n");

    return 0;
}



C#: using System;
using static System.Console; 
using LI = System.Collections.Generic.SortedSet<int>;

class Program {

  static LI unl(LI res, LI set, int lft, int mul = 1, int vlu = 0) {
    if (lft == 0) res.Add(vlu);
    else if (lft > 0) foreach (int itm in set)
      res = unl(res, set, lft - itm, mul * 10, vlu + itm * mul);
    return res; }

  static void Main(string[] args) { WriteLine(string.Join(" ",
      unl(new LI {}, new LI { 2, 3, 5, 7 }, 13))); }
}
Task: Take notes on the command line

C: #include <stdio.h>
#include <time.h>

#define note_file "NOTES.TXT"

int main(int argc, char**argv)
{
	FILE *note = 0;
	time_t tm;
	int i;
	char *p;

	if (argc < 2) {
		if ((note = fopen(note_file, "r")))
			while ((i = fgetc(note)) != EOF)
				putchar(i);

	} else if ((note = fopen(note_file, "a"))) {
		tm = time(0);
		p = ctime(&tm);

		
		while (*p) fputc(*p != '\n'?*p:'\t', note), p++;

		for (i = 1; i < argc; i++)
			fprintf(note, "%s%c", argv[i], 1 + i - argc ? ' ' : '\n');
	}

	if (note) fclose(note);
	return 0;
}



C#: using System;
using System.IO;
using System.Text;

namespace RosettaCode
{
  internal class Program
  {
    private const string FileName = "NOTES.TXT";

    private static void Main(string[] args)
    {
      if (args.Length==0)
      {
        string txt = File.ReadAllText(FileName);
        Console.WriteLine(txt);
      }
      else
      {
        var sb = new StringBuilder();
        sb.Append(DateTime.Now).Append("\n\t");
        foreach (string s in args)
          sb.Append(s).Append(" ");
        sb.Append("\n");

        if (File.Exists(FileName))
          File.AppendAllText(FileName, sb.ToString());
        else
          File.WriteAllText(FileName, sb.ToString());
      }
    }
  }
}