WeixiangYan/CodeTransOcean huggingface dataset:
Task: Verify distribution uniformity_Chi-squared test

C: #include <stdlib.h>
#include <stdio.h>
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

typedef double (* Ifctn)( double t);

double Simpson3_8( Ifctn f, double a, double b, int N)
{
    int j;
    double l1;
    double h = (b-a)/N;
    double h1 = h/3.0;
    double sum = f(a) + f(b);

    for (j=3*N-1; j>0; j--) {
        l1 = (j%3)? 3.0 : 2.0;
        sum += l1*f(a+h1*j) ;
    }
    return h*sum/8.0;
}

#define A 12
double Gamma_Spouge( double z )
{
    int k;
    static double cspace[A];
    static double *coefs = NULL;
    double accum;
    double a = A;

    if (!coefs) {
        double k1_factrl = 1.0;
        coefs = cspace;
        coefs[0] = sqrt(2.0*M_PI);
        for(k=1; k<A; k++) {
            coefs[k] = exp(a-k) * pow(a-k,k-0.5) / k1_factrl;
            k1_factrl *= -k;
        }
    }

    accum = coefs[0];
    for (k=1; k<A; k++) {
        accum += coefs[k]/(z+k);
    }
    accum *= exp(-(z+a)) * pow(z+a, z+0.5);
    return accum/z;
}

double aa1;
double f0( double t)
{
    return  pow(t, aa1)*exp(-t); 
}

double GammaIncomplete_Q( double a, double x)
{
    double y, h = 1.5e-2;  

    
    y = aa1 = a-1;
    while((f0(y) * (x-y) > 2.0e-8) && (y < x))   y += .4;
    if (y>x) y=x;

    return 1.0 - Simpson3_8( &f0, 0, y, (int)(y/h))/Gamma_Spouge(a);
}







Python: import math
import random

def GammaInc_Q( a, x):
    a1 = a-1
    a2 = a-2
    def f0( t ):
        return t**a1*math.exp(-t)

    def df0(t):
        return (a1-t)*t**a2*math.exp(-t)
    
    y = a1
    while f0(y)*(x-y) >2.0e-8 and y < x: y += .3
    if y > x: y = x

    h = 3.0e-4
    n = int(y/h)
    h = y/n
    hh = 0.5*h
    gamax = h * sum( f0(t)+hh*df0(t) for t in ( h*j for j in xrange(n-1, -1, -1)))

    return gamax/gamma_spounge(a)

c = None
def gamma_spounge( z):
    global c
    a = 12

    if c is None:
       k1_factrl = 1.0
       c = []
       c.append(math.sqrt(2.0*math.pi))
       for k in range(1,a):
          c.append( math.exp(a-k) * (a-k)**(k-0.5) / k1_factrl )
          k1_factrl *= -k
    
    accm = c[0]
    for k in range(1,a):
        accm += c[k] / (z+k)
    accm *= math.exp( -(z+a)) * (z+a)**(z+0.5)
    return accm/z;

def chi2UniformDistance( dataSet ):
    expected = sum(dataSet)*1.0/len(dataSet)
    cntrd = (d-expected for d in dataSet)
    return sum(x*x for x in cntrd)/expected

def chi2Probability(dof, distance):
    return 1.0 - GammaInc_Q( 0.5*dof, 0.5*distance)

def chi2IsUniform(dataSet, significance):
    dof = len(dataSet)-1
    dist = chi2UniformDistance(dataSet)
    return chi2Probability( dof, dist ) > significance

dset1 = [ 199809, 200665, 199607, 200270, 199649 ]
dset2 = [ 522573, 244456, 139979,  71531,  21461 ]

for ds in (dset1, dset2):
    print "Data set:", ds
    dof = len(ds)-1
    distance =chi2UniformDistance(ds)
    print "dof: %d distance: %.4f" % (dof, distance),
    prob = chi2Probability( dof, distance)
    print "probability: %.4f"%prob,
    print "uniform? ", "Yes"if chi2IsUniform(ds,0.05) else "No"
Task: Call a function

C: 
f();


g(1, 2, 3);


int op_arg();
int main()
{
	op_arg(1);
	op_arg(1, 2);
	op_arg(1, 2, 3);
	return 0;
}
int op_arg(int a, int b)
{
	printf("%d %d %d\n", a, b, (&b)[1]);
	return a;
}  


void h(int a, ...)
{
	va_list ap;
	va_start(ap);
	...
}

h(1, 2, 3, 4, "abcd", (void*)0);


struct v_args {
    int arg1;
    int arg2;
    char _sentinel;
};

void _v(struct v_args args)
{
    printf("%d, %d\n", args.arg1, args.arg2);
}

#define v(...) _v((struct v_args){__VA_ARGS__})

v(.arg2 = 5, .arg1 = 17); 

v(.arg2=1); 
v();  


printf("%p", f); 


double a = asin(1);














Python: def no_args():
    pass

no_args()

def fixed_args(x, y):
    print('x=%r, y=%r' % (x, y))

fixed_args(1, 2)        


fixed_args(y=2, x=1)


myargs=(1,2) 
fixed_args(*myargs)

def opt_args(x=1):
    print(x)

opt_args()              
opt_args(3.141)         

def var_args(*v):
    print(v)

var_args(1, 2, 3)       
var_args(1, (2,3))      
var_args()              


fixed_args(y=2, x=1)    


if 1:
    no_args()


assert no_args() is None

def return_something():
    return 1
x = return_something()

def is_builtin(x):
	print(x.__name__ in dir(__builtins__))

is_builtin(pow)         
is_builtin(is_builtin)  



def takes_anything(*args, **kwargs):
    for each in args:
        print(each)
    for key, value in sorted(kwargs.items()):
        print("%s:%s" % (key, value))
    
    wrapped_fn(*args, **kwargs)
Task: GUI component interaction

C: #include <windows.h>
#include "resource.h"

BOOL CALLBACK DlgProc( HWND hwnd, UINT msg, WPARAM wPar, LPARAM lPar ) {
    switch( msg ) {

        case WM_INITDIALOG:
            srand( GetTickCount() );
            SetDlgItemInt( hwnd, IDC_INPUT, 0, FALSE );
            break;

        case WM_COMMAND:
            switch( LOWORD(wPar) ) {
                case IDC_INCREMENT: {
                    UINT n = GetDlgItemInt( hwnd, IDC_INPUT, NULL, FALSE );
                    SetDlgItemInt( hwnd, IDC_INPUT, ++n, FALSE );
                    } break;
                case IDC_RANDOM: {
                    int reply = MessageBox( hwnd,
                        "Do you really want to\nget a random number?",
                        "Random input confirmation", MB_ICONQUESTION|MB_YESNO );
                    if( reply == IDYES )
                        SetDlgItemInt( hwnd, IDC_INPUT, rand(), FALSE );
                    } break;
                case IDC_QUIT:
                    SendMessage( hwnd, WM_CLOSE, 0, 0 );
                    break;
                default: ;
            }
            break;

        case WM_CLOSE: {
            int reply = MessageBox( hwnd,
                "Do you really want to quit?",
                "Quit confirmation", MB_ICONQUESTION|MB_YESNO );
            if( reply == IDYES )
                EndDialog( hwnd, 0 );
            } break;

        default: ;
    }

    return 0;
}

int WINAPI WinMain( HINSTANCE hInst, HINSTANCE hPInst, LPSTR cmdLn, int show ) {
    return DialogBox( hInst, MAKEINTRESOURCE(IDD_DLG), NULL, DlgProc );
}







Python: import random, tkMessageBox
from Tkinter import *
window = Tk()
window.geometry("300x50+100+100")
options = { "padx":5, "pady":5}
s=StringVar()
s.set(1)
def increase():
    s.set(int(s.get())+1)
def rand():
    if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
        s.set(random.randrange(0,5000))
def update(e):
    if not e.char.isdigit():
        tkMessageBox.showerror('Error', 'Invalid input !') 
        return "break"
e = Entry(text=s)
e.grid(column=0, row=0, **options)
e.bind('<Key>', update)
b1 = Button(text="Increase", command=increase, **options )
b1.grid(column=1, row=0, **options)
b2 = Button(text="Random", command=rand, **options)
b2.grid(column=2, row=0, **options)
mainloop()
Task: One of n lines in a file

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

inline int irand(int n)
{
	int r, randmax = RAND_MAX/n * n;
	while ((r = rand()) >= randmax);
	return r / (randmax / n);
}

inline int one_of_n(int n)
{
	int i, r = 0;
	for (i = 1; i < n; i++) if (!irand(i + 1)) r = i;
	return r;
}

int main(void)
{
	int i, r[10] = {0};

	for (i = 0; i < 1000000; i++, r[one_of_n(10)]++);
	for (i = 0; i < 10; i++)
		printf("%d%c", r[i], i == 9 ? '\n':' ');

	return 0;
}







Python: from random import randrange
try:
    range = xrange
except: pass

def one_of_n(lines): 
    choice = None
    for i, line in enumerate(lines):
        if randrange(i+1) == 0:
            choice = line
    return choice
            
def one_of_n_test(n=10, trials=1000000):
    bins = [0] * n
    if n:
        for i in range(trials):
            bins[one_of_n(range(n))] += 1
    return bins

print(one_of_n_test())
Task: Self-describing numbers

C: #include <stdio.h>

inline int self_desc(unsigned long long xx)
{
	register unsigned int d, x;
	unsigned char cnt[10] = {0}, dig[10] = {0};
 
	for (d = 0; xx > ~0U; xx /= 10)
		cnt[ dig[d++] = xx % 10 ]++;
 
	for (x = xx; x; x /= 10)
		cnt[ dig[d++] = x % 10 ]++;
 
	while(d-- && dig[x++] == cnt[d]);
 
	return d == -1;
}
 
int main()
{
	int i;
	for (i = 1; i < 100000000; i++) 
		if (self_desc(i)) printf("%d\n", i);
 
	return 0;
}







Python: >>> def isSelfDescribing(n):
	s = str(n)
	return all(s.count(str(i)) == int(ch) for i, ch in enumerate(s))

>>> [x for x in range(4000000) if isSelfDescribing(x)]
[1210, 2020, 21200, 3211000]
>>> [(x, isSelfDescribing(x)) for x in (1210, 2020, 21200, 3211000, 42101000, 521001000, 6210001000)]
[(1210, True), (2020, True), (21200, True), (3211000, True), (42101000, True), (521001000, True), (6210001000, True)]
Task: Repeat

C: #include <stdio.h>

void repeat(void (*f)(void), unsigned int n) {
 while (n-->0)
  (*f)(); 
}

void example() {
 printf("Example\n");
}

int main(int argc, char *argv[]) {
 repeat(example, 4);
 return 0;
}







Python: 
def repeat(f,n):
  for i in range(n):
    f();

def procedure():
  print("Example");

repeat(procedure,3);
Task: Sparkline in unicode

C: #include<string.h>
#include<stdlib.h>
#include<locale.h>
#include<stdio.h>
#include<wchar.h>
#include<math.h>

int main(int argC,char* argV[])
{
	double* arr,min,max;
	char* str;
	int i,len;
	if(argC == 1)
		printf("Usage : %s <data points separated by spaces or commas>",argV[0]);
	else{
		arr = (double*)malloc((argC-1)*sizeof(double));
		for(i=1;i<argC;i++){
			len = strlen(argV[i]);
			
			if(argV[i][len-1]==','){
				str = (char*)malloc(len*sizeof(char));
				strncpy(str,argV[i],len-1);
				arr[i-1] = atof(str);
				free(str);
			}
			else
				arr[i-1] = atof(argV[i]);
			if(i==1){
				min = arr[i-1];
				max = arr[i-1];
			}
			else{
				min=(min<arr[i-1]?min:arr[i-1]);
				max=(max>arr[i-1]?max:arr[i-1]);
			}
		}
		
		printf("\n%Max : %lf,Min : %lf,Range : %lf\n",max,min,max-min);
		
		setlocale(LC_ALL, "");
		
		for(i=1;i<argC;i++){
			printf("%lc", (wint_t)(9601 + (int)ceil((arr[i-1]-min)/(max-min)*7)));
		}
	}
	return 0;
}







Python: 


bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)

def sparkline(numbers):
    mn, mx = min(numbers), max(numbers)
    extent = mx - mn
    sparkline = ''.join(bar[min([barcount - 1,
                                 int((n - mn) / extent * barcount)])]
                        for n in numbers)
    return mn, mx, sparkline

if __name__ == '__main__':
    import re
    
    for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
                 "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
                 "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
        print("\nNumbers:", line)
        numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
        mn, mx, sp = sparkline(numbers)
        print('  min: %5f; max: %5f' % (mn, mx))
        print("  " + sp)
Task: Compiler_AST interpreter

C: 
count = 1;
n = 1;
limit = 100;
while (n < limit) {
    k=3;
    p=1;
    n=n+2;
    while ((k*k<=n) && (p)) {
        p=n/k*k!=n;
        k=k+2;
    }
    if (p) {
        print(n, " is prime\n");
        count = count + 1;
    }
}
print("Total primes found: ", count, "\n");







Python: def load_ast()
    line = readline()
    
    line_list = tokenize the line, respecting double quotes

    text = line_list[0] 

    if text == ";"   
        return NULL

    node_type = text 

    
    
    
    if len(line_list) > 1
        return make_leaf(node_type, line_list[1])

    left = load_ast()
    right = load_ast()
    return make_node(node_type, left, right)
Task: Modular inverse

C: #include <stdio.h>

int mul_inv(int a, int b)
{
	int b0 = b, t, q;
	int x0 = 0, x1 = 1;
	if (b == 1) return 1;
	while (a > 1) {
		q = a / b;
		t = b, b = a % b, a = t;
		t = x0, x0 = x1 - q * x0, x1 = t;
	}
	if (x1 < 0) x1 += b0;
	return x1;
}

int main(void) {
	printf("%d\n", mul_inv(42, 2017));
	return 0;
}







Python: >>> def extended_gcd(aa, bb):
    lastremainder, remainder = abs(aa), abs(bb)
    x, lastx, y, lasty = 0, 1, 1, 0
    while remainder:
        lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)
        x, lastx = lastx - quotient*x, x
        y, lasty = lasty - quotient*y, y
    return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)

>>> def modinv(a, m):
	g, x, y = extended_gcd(a, m)
	if g != 1:
		raise ValueError
	return x % m

>>> modinv(42, 2017)
1969
>>>
Task: Simulate input_Mouse

C: #define WINVER 0x500
#include<windows.h>

int main()
{
	int maxX = GetSystemMetrics(SM_CXSCREEN), maxY = GetSystemMetrics(SM_CYSCREEN);
	int x = maxX/2, y = maxY/2;
	double factorX = 65536.0 / maxX,factorY = 65536.0 / maxY;
	
	INPUT ip;
	
	ZeroMemory(&ip,sizeof(ip));
	
	ip.type = INPUT_MOUSE;
	
	while(x > 5 || y < maxY-5){

	ip.mi.mouseData = 0;
	ip.mi.dx = x * factorX;
	ip.mi.dy = y * factorY;
	ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE;
		
	SendInput(1,&ip,sizeof(ip));
	Sleep(1);
	if(x>3)	
		x-=1;
	if(y<maxY-3)
		y+=1;
	}
	
	ip.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP;
	
	SendInput(1,&ip,sizeof(ip));
	
	return 0;
}







Python: import ctypes

def click():
    ctypes.windll.user32.mouse_event(0x2, 0,0,0,0)    
    ctypes.windll.user32.mouse_event(0x4, 0,0,0,0)    

click()
Task: Hello world_Web server

C: #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <err.h>

char response[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html><html><head><title>Bye-bye baby bye-bye</title>"
"<style>body { background-color: #111 }"
"h1 { font-size:4cm; text-align: center; color: black;"
" text-shadow: 0 0 2mm red}</style></head>"
"<body><h1>Goodbye, world!</h1></body></html>\r\n";

int main()
{
  int one = 1, client_fd;
  struct sockaddr_in svr_addr, cli_addr;
  socklen_t sin_len = sizeof(cli_addr);

  int sock = socket(AF_INET, SOCK_STREAM, 0);
  if (sock < 0)
    err(1, "can't open socket");

  setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

  int port = 8080;
  svr_addr.sin_family = AF_INET;
  svr_addr.sin_addr.s_addr = INADDR_ANY;
  svr_addr.sin_port = htons(port);

  if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
    close(sock);
    err(1, "Can't bind");
  }

  listen(sock, 5);
  while (1) {
    client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
    printf("got connection\n");

    if (client_fd == -1) {
      perror("Can't accept");
      continue;
    }

    write(client_fd, response, sizeof(response) - 1); 
    close(client_fd);
  }
}







Python: from wsgiref.simple_server import make_server

def app(environ, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    yield b"<h1>Goodbye, World!</h1>"

server = make_server('127.0.0.1', 8080, app)
server.serve_forever()
Task: Sunflower fractal

C: 

#include<graphics.h>
#include<math.h>

#define pi M_PI

void sunflower(int winWidth, int winHeight, double diskRatio, int iter){
	double factor = .5 + sqrt(1.25),r,theta;
	double x = winWidth/2.0, y = winHeight/2.0;
	double maxRad = pow(iter,factor)/iter;
	
	int i;
	
	setbkcolor(LIGHTBLUE);
	
	for(i=0;i<=iter;i++){
		r = pow(i,factor)/iter;
		
		r/maxRad < diskRatio?setcolor(BLACK):setcolor(YELLOW);
		
		theta = 2*pi*factor*i;
		circle(x + r*sin(theta), y + r*cos(theta), 10 * i/(1.0*iter));
	}
}

int main()
{
	initwindow(1000,1000,"Sunflower...");
	
	sunflower(1000,1000,0.5,3000);
	
	getch();
	
	closegraph();
	
	return 0;
}







Python: from turtle import *
from math import *



iter = 3000
diskRatio = .5

factor = .5 + sqrt(1.25)

screen = getscreen()

(winWidth, winHeight) = screen.screensize()





x = 0.0
y = 0.0

maxRad = pow(iter,factor)/iter;

bgcolor("light blue")

hideturtle()

tracer(0, 0)

for i in range(iter+1):
    r = pow(i,factor)/iter;
    
    if r/maxRad < diskRatio:
        pencolor("black")
    else:
        pencolor("yellow")
 
    theta = 2*pi*factor*i;
        
    up()
    
    setposition(x + r*sin(theta), y + r*cos(theta))
    
    down()
       
    circle(10.0 * i/(1.0*iter))
    
update()

done()
Task: Air mass

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

#define DEG 0.017453292519943295769236907684886127134  
#define RE 6371000.0 
#define DD 0.001 
#define FIN 10000000.0 

static double rho(double a) {
    
    return exp(-a / 8500.0);
}

static double height(double a, double z, double d) {
    
    
    
    double aa = RE + a;
    double hh = sqrt(aa * aa + d * d - 2.0 * d * aa * cos((180 - z) * DEG));
    return hh - RE;
}

static double column_density(double a, double z) {
    
    double sum = 0.0, d = 0.0;
    while (d < FIN) {
        
        double delta = DD * d;
        if (delta < DD)
            delta = DD;
        sum += rho(height(a, z, d + 0.5 * delta)) * delta;
        d += delta;
    }
    return sum;
}

static double airmass(double a, double z) {
    return column_density(a, z) / column_density(a, 0.0);
}

int main() {
    puts("Angle     0 m              13700 m");
    puts("------------------------------------");
    for (double z = 0; z <= 90; z+= 5) {
        printf("%2.0f      %11.8f      %11.8f\n",
               z, airmass(0.0, z), airmass(13700.0, z));
    }
}







Python: 

from math import sqrt, cos, exp

DEG = 0.017453292519943295769236907684886127134  
RE = 6371000                                     
dd = 0.001      
FIN = 10000000  
 
def rho(a):
    
    return exp(-a / 8500.0)
 
def height(a, z, d):
     
    return sqrt((RE + a)**2 + d**2 - 2 * d * (RE + a) * cos((180 - z) * DEG)) - RE
 
def column_density(a, z):
    
    dsum, d = 0.0, 0.0
    while d < FIN:
        delta = max(dd, (dd)*d)  
        dsum += rho(height(a, z, d + 0.5 * delta)) * delta
        d += delta
    return dsum

def airmass(a, z):
    return column_density(a, z) / column_density(a, 0)

print('Angle           0 m          13700 m\n', '-' * 36)
for z in range(0, 91, 5):
    print(f"{z: 3d}      {airmass(0, z): 12.7f}    {airmass(13700, z): 12.7f}")
Task: Day of the week of Christmas and New Year

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

int main() {
    struct tm t[2];
    strptime("2021-12-25", "%F", &t[0]);
    strptime("2022-01-01", "%F", &t[1]);
    for (int i=0; i<2; i++) {
        char buf[32];
        strftime(buf, 32, "%F is a %A", &t[i]);
        puts(buf);
    }
    return 0;
}







Python: import datetime

weekDays = ("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday")
thisXMas  = datetime.date(2021,12,25)
thisXMasDay = thisXMas.weekday()
thisXMasDayAsString = weekDays[thisXMasDay]
print("This year's Christmas is on a {}".format(thisXMasDayAsString))

nextNewYear = datetime.date(2022,1,1)
nextNewYearDay = nextNewYear.weekday()
nextNewYearDayAsString = weekDays[nextNewYearDay]
print("Next new year is on a {}".format(nextNewYearDayAsString))
Task: Own digits power sum

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

#define MAX_DIGITS 9

int digits[MAX_DIGITS];

void getDigits(int i) {
    int ix = 0;
    while (i > 0) {
        digits[ix++] = i % 10;
        i /= 10;
    }
}

int main() {
    int n, d, i, max, lastDigit, sum, dp;
    int powers[10] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81};
    printf("Own digits power sums for N = 3 to 9 inclusive:\n");
    for (n = 3; n < 10; ++n) {
        for (d = 2; d < 10; ++d) powers[d] *= d;
        i = (int)pow(10, n-1);
        max = i * 10;
        lastDigit = 0;
        while (i < max) {
            if (!lastDigit) {
                getDigits(i);
                sum = 0;
                for (d = 0; d < n; ++d) {
                    dp = digits[d];
                    sum += powers[dp];
                }
            } else if (lastDigit == 1) {
                sum++;
            } else {
                sum += powers[lastDigit] - powers[lastDigit-1];
            }
            if (sum == i) {
                printf("%d\n", i);
                if (lastDigit == 0) printf("%d\n", i + 1);
                i += 10 - lastDigit;
                lastDigit = 0;
            } else if (sum > i) {
                i += 10 - lastDigit;
                lastDigit = 0;
            } else if (lastDigit < 9) {
                i++;
                lastDigit++;
            } else {
                i++;
                lastDigit = 0;
            }
        }
    }
    return 0;
}







Python: 

def isowndigitspowersum(integer):
    
    digits = [int(c) for c in str(integer)]
    exponent = len(digits)
    return sum(x ** exponent for x in digits) == integer

print("Own digits power sums for N = 3 to 9 inclusive:")
for i in range(100, 1000000000):
    if isowndigitspowersum(i):
        print(i)
Task: Klarner-Rado sequence

C: #include <stdio.h>

#define ELEMENTS 10000000U

void make_klarner_rado(unsigned int *dst, unsigned int n) {
    unsigned int i, i2 = 0, i3 = 0;
    unsigned int m, m2 = 1, m3 = 1;

    for (i = 0; i < n; ++i) {
        dst[i] = m = m2 < m3 ? m2 : m3;
        if (m2 == m) m2 = dst[i2++] << 1 | 1;
        if (m3 == m) m3 = dst[i3++] * 3 + 1;
    }
}

int main(void) {
    static unsigned int klarner_rado[ELEMENTS];
    unsigned int i;

    make_klarner_rado(klarner_rado, ELEMENTS);

    for (i = 0; i < 99; ++i)
        printf("%u ", klarner_rado[i]);
    for (i = 100; i <= ELEMENTS; i *= 10)
        printf("%u\n", klarner_rado[i - 1]);

    return 0;
}







Python: def KlarnerRado(N):
    K = [1]
    for i in range(N):
        j = K[i]
        firstadd, secondadd = 2 * j + 1, 3 * j + 1
        if firstadd < K[-1]:
            for pos in range(len(K)-1, 1, -1):
                if K[pos] < firstadd < K[pos + 1]:
                    K.insert(pos + 1, firstadd)
                    break
        elif firstadd > K[-1]:
            K.append(firstadd)
        if secondadd < K[-1]:
            for pos in range(len(K)-1, 1, -1):
                if K[pos] < secondadd < K[pos + 1]:
                    K.insert(pos + 1, secondadd)
                    break
        elif secondadd > K[-1]:
            K.append(secondadd)

    return K

kr1m = KlarnerRado(100_000)

print('First 100 Klarner-Rado sequence numbers:')
for idx, v in enumerate(kr1m[:100]):
    print(f'{v: 4}', end='\n' if (idx + 1) % 20 == 0 else '')
for n in [1000, 10_000, 100_000]:
    print(f'The {n :,}th Klarner-Rado number is {kr1m[n-1] :,}')
Task: Bitmap_Bézier curves_Cubic

C: void cubic_bezier(
       	image img,
        unsigned int x1, unsigned int y1,
        unsigned int x2, unsigned int y2,
        unsigned int x3, unsigned int y3,
        unsigned int x4, unsigned int y4,
        color_component r,
        color_component g,
        color_component b );







Python: def cubicbezier(self, x0, y0, x1, y1, x2, y2, x3, y3, n=20):
    pts = []
    for i in range(n+1):
        t = i / n
        a = (1. - t)**3
        b = 3. * t * (1. - t)**2
        c = 3.0 * t**2 * (1.0 - t)
        d = t**3
        
        x = int(a * x0 + b * x1 + c * x2 + d * x3)
        y = int(a * y0 + b * y1 + c * y2 + d * y3)
        pts.append( (x, y) )
    for i in range(n):
        self.line(pts[i][0], pts[i][1], pts[i+1][0], pts[i+1][1])
Bitmap.cubicbezier = cubicbezier

bitmap = Bitmap(17,17)
bitmap.cubicbezier(16,1, 1,4, 3,16, 15,11)
bitmap.chardisplay()