WeixiangYan/CodeTransOcean huggingface dataset:
Task: Variable-length quantity

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

void to_seq(uint64_t x, uint8_t *out)
{
	int i, j;
	for (i = 9; i > 0; i--) {
		if (x & 127ULL << i * 7) break;
	}
	for (j = 0; j <= i; j++)
		out[j] = ((x >> ((i - j) * 7)) & 127) | 128;

	out[i] ^= 128;
}

uint64_t from_seq(uint8_t *in)
{
	uint64_t r = 0;

	do {
		r = (r << 7) | (uint64_t)(*in & 127);
	} while (*in++ & 128);

	return r;
}

int main()
{
	uint8_t s[10];
	uint64_t x[] = { 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL};

	int i, j;
	for (j = 0; j < sizeof(x)/8; j++) {
		to_seq(x[j], s);
		printf("seq from %llx: [ ", x[j]);

		i = 0;
		do { printf("%02x ", s[i]); } while ((s[i++] & 128));
		printf("] back: %llx\n", from_seq(s));
	}

	return 0;
}


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

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

    os << "[ ";
    if (it != end) {
        os << std::setfill('0') << std::setw(2) << (uint32_t)*it;
        it = std::next(it);
    }
    while (it != end) {
        os << ' ' << std::setfill('0') << std::setw(2) << (uint32_t)*it;
        it = std::next(it);
    }
    return os << " ]";
}

std::vector<uint8_t> to_seq(uint64_t x) {
    int i;
    for (i = 9; i > 0; i--) {
        if (x & 127ULL << i * 7) {
            break;
        }
    }

    std::vector<uint8_t> out;
    for (int j = 0; j <= i; j++) {
        out.push_back(((x >> ((i - j) * 7)) & 127) | 128);
    }
    out[i] ^= 128;
    return out;
}

uint64_t from_seq(const std::vector<uint8_t> &seq) {
    uint64_t r = 0;

    for (auto b : seq) {
        r = (r << 7) | (b & 127);
    }

    return r;
}

int main() {
    std::vector<uint64_t> src{ 0x7f, 0x4000, 0, 0x3ffffe, 0x1fffff, 0x200000, 0x3311a1234df31413ULL };

    for (auto x : src) {
        auto s = to_seq(x);
        std::cout << std::hex;
        std::cout << "seq from " << x << ' ' << s << " back: " << from_seq(s) << '\n';
        std::cout << std::dec;
    }

    return 0;
}
Task: Record sound

C: #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>

void * record(size_t bytes)
{
	int fd;
	if (-1 == (fd = open("/dev/dsp", O_RDONLY))) return 0;
	void *a = malloc(bytes);
	read(fd, a, bytes);
	close(fd);
	return a;
}

int play(void *buf, size_t len)
{
	int fd;
	if (-1 == (fd = open("/dev/dsp", O_WRONLY))) return 0;
	write(fd, buf, len);
	close(fd);
	return 1;
}

int main()
{
	void *p = record(65536);
	play(p, 65536);
	return 0;
}


C++: #include <iostream>
#include <string>
#include <windows.h>
#include <mmsystem.h>

#pragma comment ( lib, "winmm.lib" )
using namespace std;

class recorder
{
public:
    void start()
    {
	paused = rec = false; action = "IDLE";
	while( true )
	{
	    cout << endl << "==" << action << "==" << endl << endl;
	    cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl;
	    char c; cin >> c;
	    if( c > '0' && c < '6' )
	    {
		switch( c )
		{
		    case '1': record(); break;
		    case '2': play();   break;
		    case '3': pause();  break;
		    case '4': stop();   break;
		    case '5': stop();   return;
		}
	    }
	}
    }
private:
    void record()
    {
	if( mciExecute( "open new type waveaudio alias my_sound") )
	{ 
	    mciExecute( "record my_sound" ); 
	    action = "RECORDING"; rec = true; 
	}
    }
    void play()
    {
	if( paused )
	    mciExecute( "play my_sound" );
	else
	    if( mciExecute( "open tmp.wav alias my_sound" ) )
		mciExecute( "play my_sound" );

	action = "PLAYING";
	paused = false;
    }
    void pause()
    {
	if( rec ) return;
	mciExecute( "pause my_sound" );
	paused = true; action = "PAUSED";
    }
    void stop()
    {
	if( rec )
	{
	    mciExecute( "stop my_sound" );
	    mciExecute( "save my_sound tmp.wav" );
	    mciExecute( "close my_sound" );
	    action = "IDLE"; rec = false;
	}
	else
	{
	    mciExecute( "stop my_sound" );
	    mciExecute( "close my_sound" );
	    action = "IDLE";
	}
    }
    bool mciExecute( string cmd )
    {
	if( mciSendString( cmd.c_str(), NULL, 0, NULL ) )
	{
	    cout << "Can't do this: " << cmd << endl;
	    return false;
	}
	return true;
    }

    bool paused, rec;
    string action;
};

int main( int argc, char* argv[] )
{
    recorder r; r.start();
    return 0;
}
Task: String case

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


void str_toupper(char *s)
{
    while(*s)
    {
        *s=toupper(*s);
        s++;
    }
}



void str_tolower(char *s)
{
    while(*s)
    {
        *s=tolower(*s);
        s++;
    }
}

int main(int argc, char *argv[])
{
    char t[255]="alphaBETA";
    str_toupper(t);
    printf("uppercase: %s\n", t);
    str_tolower(t);
    printf("lowercase: %s\n", t);
    return 0;
}


C++: #include <algorithm>
#include <string>
#include <cctype>



void str_toupper(std::string &str) {
  std::transform(str.begin(), 
                 str.end(), 
                 str.begin(),
                 (int(*)(int)) std::toupper);
}



void str_tolower(std::string &str) {
  std::transform(str.begin(), 
                 str.end(), 
                 str.begin(),
                 (int(*)(int)) std::tolower);
}
Task: User input_Graphical

C: #include <gtk/gtk.h>

void ok_hit(GtkButton *o, GtkWidget **w)
{
  GtkMessageDialog *msg;

  gdouble v = gtk_spin_button_get_value((GtkSpinButton *)w[1]);
  const gchar *c = gtk_entry_get_text((GtkEntry *)w[0]);

  msg = (GtkMessageDialog *)
    gtk_message_dialog_new(NULL,
			   GTK_DIALOG_MODAL,
			   (v==75000) ? GTK_MESSAGE_INFO : GTK_MESSAGE_ERROR,
			   GTK_BUTTONS_OK,
			   "You wrote '%s' and selected the number %d%s",
			   c, (gint)v,
			   (v==75000) ? "" : " which is wrong (75000 expected)!");
  gtk_widget_show_all(GTK_WIDGET(msg));
  (void)gtk_dialog_run(GTK_DIALOG(msg));
  gtk_widget_destroy(GTK_WIDGET(msg));
  if ( v==75000 ) gtk_main_quit();
}

int main(int argc, char **argv)
{
  GtkWindow *win;
  GtkEntry *entry;
  GtkSpinButton *spin;
  GtkButton *okbutton;
  GtkLabel *entry_l, *spin_l;
  GtkHBox *hbox[2];
  GtkVBox *vbox;
  GtkWidget *widgs[2];

  gtk_init(&argc, &argv);
  
  win = (GtkWindow *)gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(win, "Insert values");
  
  entry_l = (GtkLabel *)gtk_label_new("Insert a string");
  spin_l =  (GtkLabel *)gtk_label_new("Insert 75000");

  entry = (GtkEntry *)gtk_entry_new();
  spin = (GtkSpinButton *)gtk_spin_button_new_with_range(0, 80000, 1);

  widgs[0] = GTK_WIDGET(entry);
  widgs[1] = GTK_WIDGET(spin);

  okbutton = (GtkButton *)gtk_button_new_with_label("Ok");
  
  hbox[0] = (GtkHBox *)gtk_hbox_new(FALSE, 1);
  hbox[1] = (GtkHBox *)gtk_hbox_new(FALSE, 1);

  vbox = (GtkVBox *)gtk_vbox_new(TRUE, 1);

  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry_l));
  gtk_container_add(GTK_CONTAINER(hbox[0]), GTK_WIDGET(entry));
  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin_l));
  gtk_container_add(GTK_CONTAINER(hbox[1]), GTK_WIDGET(spin));

  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[0]));
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(hbox[1]));
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(okbutton));

  gtk_container_add(GTK_CONTAINER(win), GTK_WIDGET(vbox));

  g_signal_connect(G_OBJECT(win), "delete-event", (GCallback)gtk_main_quit, NULL);
  g_signal_connect(G_OBJECT(okbutton), "clicked", (GCallback)ok_hit, widgs);

  gtk_widget_show_all(GTK_WIDGET(win));
  gtk_main();

  return 0;
}


C++: #ifndef TASK_H
#define TASK_H

#include <QWidget>

class QLabel ;
class QLineEdit ;
class QVBoxLayout ;
class QHBoxLayout ;

class EntryWidget : public QWidget {

   Q_OBJECT 
public :
   EntryWidget( QWidget *parent = 0 ) ;
private :
   QHBoxLayout *upperpart , *lowerpart ;
   QVBoxLayout *entryLayout ;
   QLineEdit *stringinput ;
   QLineEdit *numberinput ;
   QLabel *stringlabel ;
   QLabel *numberlabel ;
} ;

#endif
Task: MD5

C: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/md5.h>

const char *string = "The quick brown fox jumped over the lazy dog's back";

int main()
{
  int i;
  unsigned char result[MD5_DIGEST_LENGTH];

  MD5(string, strlen(string), result);

  
  for(i = 0; i < MD5_DIGEST_LENGTH; i++)
    printf("%02x", result[i]);
  printf("\n");

  return EXIT_SUCCESS;
}


C++: #include <string>
#include <iostream>
#include "Poco/MD5Engine.h"
#include "Poco/DigestStream.h"

using Poco::DigestEngine ;
using Poco::MD5Engine ;
using Poco::DigestOutputStream ;

int main( ) {
   std::string myphrase ( "The quick brown fox jumped over the lazy dog's back" ) ;
   MD5Engine md5 ;
   DigestOutputStream outstr( md5 ) ;
   outstr << myphrase ;
   outstr.flush( ) ; 
   const DigestEngine::Digest& digest = md5.digest( ) ;
   std::cout << myphrase << " as a MD5 digest :\n" << DigestEngine::digestToHex( digest ) 
      << " !" << std::endl ;
   return 0 ;
}
Task: Date manipulation

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

int main()
{
  struct tm ts;
  time_t t;
  const char *d = "March 7 2009 7:30pm EST";
  
  strptime(d, "%B %d %Y %I:%M%p %Z", &ts);
  
  t = mktime(&ts);
  t += 12*60*60;
  printf("%s", ctime(&t));

  return EXIT_SUCCESS;
}


C++: #include <string>
#include <iostream>
#include <boost/date_time/local_time/local_time.hpp>
#include <sstream>
#include <boost/date_time/gregorian/gregorian.hpp>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <cstdlib>
#include <locale>


int main( ) {
   std::string datestring ("March 7 2009 7:30pm EST" ) ;
   
   
   
   std::vector<std::string> elements ;
   
   boost::split( elements , datestring , boost::is_any_of( " " ) ) ;
   std::string datepart = elements[ 0 ] + " " + "0" + elements[ 1 ] + " " +
      elements[ 2 ] ; 
   std::string timepart = elements[ 3 ] ;
   std::string timezone = elements[ 4 ] ;
   const char meridians[ ] = { 'a' , 'p' } ;
   
   std::string::size_type found = timepart.find_first_of( meridians, 0 ) ;
   std::string twelve_hour ( timepart.substr( found , 1 ) ) ;
   timepart = timepart.substr( 0 , found ) ; 
   elements.clear( ) ;
   boost::split( elements , timepart , boost::is_any_of ( ":" ) ) ;
   long hour = std::atol( (elements.begin( ))->c_str( ) ) ;
   if ( twelve_hour == "p" ) 
      hour += 12 ;
   long minute = std::atol( ( elements.begin( ) + 1)->c_str( ) ) ; 
   boost::local_time::tz_database tz_db ;
   tz_db.load_from_file( "/home/ulrich/internetpages/date_time_zonespec.csv" ) ;
   
   boost::local_time::time_zone_ptr dyc = tz_db.time_zone_from_region( "America/New_York" ) ;
   
   boost::gregorian::date_input_facet *f =
      new boost::gregorian::date_input_facet( "%B %d %Y"  ) ;
   std::stringstream ss ;
   ss << datepart ;
   ss.imbue( std::locale( std::locale::classic( ) , f ) ) ;
   boost::gregorian::date d ;
   ss >> d ;
   boost::posix_time::time_duration td (  hour , minute , 0  ) ;
   
   
   boost::local_time::local_date_time lt ( d , td ,  dyc ,
	 boost::local_time::local_date_time::NOT_DATE_TIME_ON_ERROR ) ;
   std::cout << "local time: " << lt << '\n' ;
   ss.str( "" ) ;
   ss << lt ;
   
   boost::posix_time::time_duration td2 (12 , 0 , 0 , 0 ) ;
   boost::local_time::local_date_time ltlater = lt + td2 ; 
   boost::gregorian::date_facet *f2 =
      new boost::gregorian::date_facet( "%B %d %Y , %R %Z" ) ;
   std::cout.imbue( std::locale( std::locale::classic( ) , f2 ) ) ;
   std::cout << "12 hours after " << ss.str( )  << " it is " << ltlater << " !\n" ;
   
   boost::local_time::time_zone_ptr bt = tz_db.time_zone_from_region( "Europe/Berlin" ) ;
   std::cout.imbue( std::locale( "de_DE.UTF-8" ) ) ; 
   std::cout << "This corresponds to " << ltlater.local_time_in( bt ) << " in Berlin!\n" ;
   return 0 ;
}
Task: Sorting algorithms_Sleep sort

C: >>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
+++++[-<------>]>>+>,----
------<<+[->>>>>+<<<<<]>>
]>>>[<<<<[<<<[->>+<<[->+>
[-]<<]]>[-<+>]>[-<<<.>>>>
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]


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

int main(int argc, char* argv[]) {
  std::vector<std::thread> threads;

  for (int i = 1; i < argc; ++i) {
    threads.emplace_back([i, &argv]() {
      int arg = std::stoi(argv[i]);
      std::this_thread::sleep_for(std::chrono::seconds(arg));
      std::cout << argv[i] << std::endl;
    });
  }

  for (auto& thread : threads) {
    thread.join();
  }
}
Task: Loops_Nested

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

int main() {
    int a[10][10], i, j;

    srand(time(NULL));
    for (i = 0; i < 10; i++)
        for (j = 0; j < 10; j++)
            a[i][j] = rand() % 20 + 1;

    for (i = 0; i < 10; i++) {
        for (j = 0; j < 10; j++) {
            printf(" %d", a[i][j]);
            if (a[i][j] == 20)
                goto Done;
        }
        printf("\n");
    }
Done:
    printf("\n");
    return 0;
}


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

using namespace std;
int main()
{
    int arr[10][10];
    srand(time(NULL));
    for(auto& row: arr)
        for(auto& col: row)
            col = rand() % 20 + 1;

    ([&](){
       for(auto& row : arr)
           for(auto& col: row)
           {
               cout << col << endl;
               if(col == 20)return;
           }
    })();
    return 0;
}
Task: Pythagorean triples

C: #include <stdio.h>
#include <stdlib.h>
 
typedef unsigned long long xint;
typedef unsigned long ulong;

inline ulong gcd(ulong m, ulong n)
{
    ulong t;
    while (n) { t = n; n = m % n; m = t; }
    return m;
}
 
int main()
{
    ulong a, b, c, pytha = 0, prim = 0, max_p = 100;
    xint aa, bb, cc;

    for (a = 1; a <= max_p / 3; a++) {
        aa = (xint)a * a;
        printf("a = %lu\r", a); 
        fflush(stdout);

        
        for (b = a + 1; b < max_p/2; b++) {
            bb = (xint)b * b;
            for (c = b + 1; c < max_p/2; c++) {
                cc = (xint)c * c;
                if (aa + bb < cc) break;
                if (a + b + c > max_p) break;

                if (aa + bb == cc) {
                    pytha++;
                    if (gcd(a, b) == 1) prim++;
                }
            }
        }
    }
 
    printf("Up to %lu, there are %lu triples, of which %lu are primitive\n",
        max_p, pytha, prim);

    return 0;
}


C++: #include <cmath>
#include <iostream>
#include <numeric>
#include <tuple>
#include <vector>

using namespace std;

auto CountTriplets(unsigned long long maxPerimeter)
{
    unsigned long long totalCount = 0;
    unsigned long long primitveCount = 0;
    auto max_M = (unsigned long long)sqrt(maxPerimeter/2) + 1;
    for(unsigned long long m = 2; m < max_M; ++m)
    {
        for(unsigned long long n = 1 + m % 2; n < m; n+=2)
        {
            if(gcd(m,n) != 1)
            {
                continue;
            }
            
            
            
            
            
            
            auto a = m * m - n * n;
            auto b = 2 * m * n;
            auto c = m * m + n * n;
            auto perimeter = a + b + c;
            if(perimeter <= maxPerimeter)
            {
                primitveCount++;
                totalCount+= maxPerimeter / perimeter;
            }
        }
    }
    
    return tuple(totalCount, primitveCount);
}


int main()
{
    vector<unsigned long long> inputs{100, 1000, 10'000, 100'000,
        1000'000, 10'000'000, 100'000'000, 1000'000'000,
        10'000'000'000};  
    for(auto maxPerimeter : inputs)
    {
        auto [total, primitive] = CountTriplets(maxPerimeter);
        cout << "\nMax Perimeter: " << maxPerimeter << ", Total: " << total << ", Primitive: " << primitive ;
    }
}
Task: Remove duplicate elements

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

struct list_node {int x; struct list_node *next;};
typedef struct list_node node;

node * uniq(int *a, unsigned alen)
 {if (alen == 0) return NULL;
  node *start = malloc(sizeof(node));
  if (start == NULL) exit(EXIT_FAILURE);
  start->x = a[0];
  start->next = NULL;

  for (int i = 1 ; i < alen ; ++i)
     {node *n = start;
      for (;; n = n->next)
         {if (a[i] == n->x) break;
          if (n->next == NULL)
             {n->next = malloc(sizeof(node));
              n = n->next;
              if (n == NULL) exit(EXIT_FAILURE);
              n->x = a[i];
              n->next = NULL;
              break;}}}

  return start;}

int main(void)
   {int a[] = {1, 2, 1, 4, 5, 2, 15, 1, 3, 4};
    for (node *n = uniq(a, 10) ; n != NULL ; n = n->next)
        printf("%d ", n->x);
    puts("");
    return 0;}


C++: #include <set>
#include <iostream>
using namespace std;

int main() {
    typedef set<int> TySet;
    int data[] = {1, 2, 3, 2, 3, 4};

    TySet unique_set(data, data + 6);

    cout << "Set items:" << endl;
    for (TySet::iterator iter = unique_set.begin(); iter != unique_set.end(); iter++)
          cout << *iter << " ";
    cout << endl;
}
Task: Look-and-say sequence

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

int main()
{
	char *a = malloc(2), *b = 0, *x, c;
	int cnt, len = 1;

	for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
		puts(x = a);
		for (len = 0, cnt = 1; (c = *a); ) {
			if (c == *++a)
				cnt++;
			else if (c) {
				len += sprintf(b + len, "%d%c", cnt, c);
				cnt = 1;
			}
		}
	}

	return 0;
}


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

std::string lookandsay(const std::string& s)
{
    std::ostringstream r;

    for (std::size_t i = 0; i != s.length();) {
        auto new_i = s.find_first_not_of(s[i], i + 1);

        if (new_i == std::string::npos)
            new_i = s.length();

        r << new_i - i << s[i];
        i = new_i;
    }
    return r.str();
}

int main()
{
    std::string laf = "1";

    std::cout << laf << '\n';
    for (int i = 0; i < 10; ++i) {
        laf = lookandsay(laf);
        std::cout << laf << '\n';
    }
}
Task: Stack

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


#define DECL_STACK_TYPE(type, name)					\
typedef struct stk_##name##_t{type *buf; size_t alloc,len;}*stk_##name;	\
stk_##name stk_##name##_create(size_t init_size) {			\
	stk_##name s; if (!init_size) init_size = 4;			\
	s = malloc(sizeof(struct stk_##name##_t));			\
	if (!s) return 0;						\
	s->buf = malloc(sizeof(type) * init_size);			\
	if (!s->buf) { free(s); return 0; }				\
	s->len = 0, s->alloc = init_size;				\
	return s; }							\
int stk_##name##_push(stk_##name s, type item) {			\
	type *tmp;							\
	if (s->len >= s->alloc) {					\
		tmp = realloc(s->buf, s->alloc*2*sizeof(type));		\
		if (!tmp) return -1; s->buf = tmp;			\
		s->alloc *= 2; }					\
	s->buf[s->len++] = item;					\
	return s->len; }						\
type stk_##name##_pop(stk_##name s) {					\
	type tmp;							\
	if (!s->len) abort();						\
	tmp = s->buf[--s->len];						\
	if (s->len * 2 <= s->alloc && s->alloc >= 8) {			\
		s->alloc /= 2;						\
		s->buf = realloc(s->buf, s->alloc * sizeof(type));}	\
	return tmp; }							\
void stk_##name##_delete(stk_##name s) {				\
	free(s->buf); free(s); }

#define stk_empty(s) (!(s)->len)
#define stk_size(s) ((s)->len)

DECL_STACK_TYPE(int, int)

int main(void)
{
	int i;
	stk_int stk = stk_int_create(0);

	printf("pushing: ");
	for (i = 'a'; i <= 'z'; i++) {
		printf(" %c", i);
		stk_int_push(stk, i);
	}

	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	printf("\npoppoing:");
	while (stk_size(stk))
		printf(" %c", stk_int_pop(stk));
	printf("\nsize now: %d", stk_size(stk));
	printf("\nstack is%s empty\n", stk_empty(stk) ? "" : " not");

	
	stk_int_delete(stk);
	return 0;
}


C++: #include <stack>
Task: Totient function

C: 

#include<stdio.h>

int totient(int n){
	int tot = n,i;
	
	for(i=2;i*i<=n;i+=2){
		if(n%i==0){
			while(n%i==0)
				n/=i;
			tot-=tot/i;
		}
		
		if(i==2)
			i=1;
	}
	
	if(n>1)
		tot-=tot/n;
	
	return tot;
}

int main()
{
	int count = 0,n,tot;
	
	printf(" n    %c   prime",237);
        printf("\n---------------\n");
	
	for(n=1;n<=25;n++){
		tot = totient(n);
		
		if(n-1 == tot)
			count++;
		
		printf("%2d   %2d   %s\n", n, tot, n-1 == tot?"True":"False");
	}
	
	printf("\nNumber of primes up to %6d =%4d\n", 25,count);
	
	for(n = 26; n <= 100000; n++){
        tot = totient(n);
        if(tot == n-1)
			count++;
        
        if(n == 100 || n == 1000 || n%10000 == 0){
            printf("\nNumber of primes up to %6d = %4d\n", n, count);
        }
    }
	
	return 0;
}


C++: #include <cassert>
#include <iomanip>
#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_;
};

int count_primes(const totient_calculator& tc, int min, int max) {
    int count = 0;
    for (int i = min; i <= max; ++i) {
        if (tc.is_prime(i))
            ++count;
    }
    return count;
}

int main() {
    const int max = 10000000;
    totient_calculator tc(max);
    std::cout << " n  totient  prime?\n";
    for (int i = 1; i <= 25; ++i) {
        std::cout << std::setw(2) << i
            << std::setw(9) << tc.totient(i)
            << std::setw(8) << (tc.is_prime(i) ? "yes" : "no") << '\n';
    }
    for (int n = 100; n <= max; n *= 10) {
        std::cout << "Count of primes up to " << n << ": "
            << count_primes(tc, 1, n) << '\n';
    }
    return 0;
}
Task: Conditional structures

C: int a = 3;


if (a == 2) {
    puts ("a is 2"); 
} else if (a == 3) {
    puts ("a is 3");
} else {
    puts("a is 4");
}


unless (a == 2) { 
    puts ("a is 2");  
} else if (a == 3) {
    puts ("a is 3");
} else {
    puts("a is 4");
}   


switch (a) {
    case 2:
        puts ("a is 2"); 
        break;
    case 3:
        puts ("a is 3");
        break;
    case 4:
        puts ("a is 4");
        break;
    default: 
        puts("is neither");
}


C++: template<bool Condition, typename ThenType, typename Elsetype> struct ifthenelse;

template<typename ThenType, typename ElseType> struct ifthenelse<true, ThenType, ElseType>
{
  typedef ThenType type;
};

template<typename ThenType, typename ElseType> struct ifthenelse<false, ThenType, ElseType>
{
  typedef ElseType type;
};


ifthenelse<INT_MAX == 32767, 
           long int,         
           int>              
  ::type myvar;
Task: Random number generator (included)

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


int
main()
{
	int i;
	srand(time(NULL));
	for (i = 0; i < 10; i++)
		puts((rand() % 2) ? "heads" : "tails");
	return 0;
}


C++: #include <iostream>
#include <string>
#include <random>
 
int main()
{
    std::random_device rd;
    std::uniform_int_distribution<int> dist(1, 10);
    std::mt19937 mt(rd());
    
    std::cout << "Random Number (hardware): " << dist(rd) << std::endl;
    std::cout << "Mersenne twister (hardware seeded): " << dist(mt) << std::endl;
}