Truth table

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0
#define STACK_SIZE 80
#define BUFFER_SIZE 100

typedef int bool;

typedef struct {
    char name;
    bool val;
} var;

typedef struct {
    int top;
    bool els[STACK_SIZE];
} stack_of_bool;

char expr[BUFFER_SIZE];
int expr_len;
var vars[24];
int vars_len;

bool is_full(stack_of_bool *sp) {
    return sp->top == STACK_SIZE - 1;
}

bool is_empty(stack_of_bool *sp) {
    return sp->top == -1;
}

bool peek(stack_of_bool *sp) {
    if (!is_empty(sp))
        return sp->els[sp->top];
    else {
        printf("Stack is empty.\n");
        exit(1);
    }
}

void push(stack_of_bool *sp, bool val) {
    if (!is_full(sp)) {
        sp->els[++(sp->top)] = val;
    }
    else {
        printf("Stack is full.\n");
        exit(1);
    }
}

bool pop(stack_of_bool *sp) {
    if (!is_empty(sp))
        return sp->els[(sp->top)--];
    else {
        printf("\nStack is empty.\n");
        exit(1);
    }
}

void make_empty(stack_of_bool *sp) {
    sp->top = -1;
}

int elems_count(stack_of_bool *sp) {
    return (sp->top) + 1;
}

bool is_operator(const char c) {
   return c == '&' || c == '|' || c == '!' || c == '^';
}

int vars_index(const char c) {
   int i;
   for (i = 0; i < vars_len; ++i) {
       if (vars[i].name == c) return i;
   }
   return -1;
}

bool eval_expr() {
    int i, vi;
    char e;
    stack_of_bool s;
    stack_of_bool *sp = &s;
    make_empty(sp);
    for (i = 0; i < expr_len; ++i) {
        e = expr[i];
        if (e == 'T')
            push(sp, TRUE);
        else if (e == 'F')
            push(sp, FALSE);
        else if((vi = vars_index(e)) >= 0) {
            push(sp, vars[vi].val);
        }
        else switch(e) {
            case '&':
                push(sp, pop(sp) & pop(sp));
                break;
            case '|':
                push(sp, pop(sp) | pop(sp));
                break;
            case '!':
                push(sp, !pop(sp));
                break;
            case '^':
                push(sp, pop(sp) ^ pop(sp));
                break;
            default:
                printf("\nNon-conformant character '%c' in expression.\n", e);
                exit(1);
        }
    }
    if (elems_count(sp) != 1) {
        printf("\nStack should contain exactly one element.\n");
        exit(1);
    }
    return peek(sp);
}

void set_vars(int pos) {
    int i;
    if (pos > vars_len) {
        printf("\nArgument to set_vars can't be greater than the number of variables.\n");
        exit(1);
    }
    else if (pos == vars_len) {
        for (i = 0; i < vars_len; ++i) {
            printf((vars[i].val) ? "T  " : "F  ");
        }
        printf("%c\n", (eval_expr()) ? 'T' : 'F');
    }
    else {
        vars[pos].val = FALSE;
        set_vars(pos + 1);
        vars[pos].val = TRUE;
        set_vars(pos + 1);
    }
}

void process_expr() {
    int i, count = 0;
    for (i = 0; expr[i]; ++i) {
        if (!isspace(expr[i])) expr[count++] = toupper(expr[i]);
    }
    expr[count] = '\0';
}

int main() {
    int i, h;
    char e;
    printf("Accepts single-character variables (except for 'T' and 'F',\n");
    printf("which specify explicit true or false values), postfix, with\n");
    printf("&|!^ for and, or, not, xor, respectively; optionally\n");
    printf("seperated by whitespace. Just enter nothing to quit.\n");

    while (TRUE) {
        printf("\nBoolean expression: ");
        fgets(expr, BUFFER_SIZE, stdin);
        fflush(stdin);
        process_expr();
        expr_len = strlen(expr);
        if (expr_len == 0) break;
        vars_len = 0;
        for (i = 0; i < expr_len; ++i) {
            e = expr[i];
            if (!is_operator(e) && e != 'T' && e != 'F' && vars_index(e) == -1) {
                vars[vars_len].name = e;
                vars[vars_len].val = FALSE;
                vars_len++;
            }
        }
        printf("\n");
        if (vars_len == 0) {
            printf("No variables were entered.\n");
        }
        else {
            for (i = 0; i < vars_len; ++i)
                printf("%c  ", vars[i].name);
            printf("%s\n", expr);
            h = vars_len * 3 + expr_len;
            for (i = 0; i < h; ++i) printf("=");
            printf("\n");
            set_vars(0);
        }
    }
    return 0;
}

use std::{
    collections::HashMap,
    fmt::{Display, Formatter},
    iter::FromIterator,
};

#[derive(Clone, Debug)]
pub enum EvaluationError<T> {
    NoResults,
    TooManyResults,
    OperatorFailed(T),
}

pub trait Operator<T> {
    type Err;

    fn execute(&self, stack: &mut Vec<T>) -> Result<(), Self::Err>;
}

#[derive(Clone, Copy, Debug)]
enum Element<O> {
    Operator(O),
    Variable(usize),
}

#[derive(Clone, Debug)]
pub struct Expression<O> {
    elements: Vec<Element<O>>,
    symbols: Vec<String>,
}

impl<O> Expression<O> {
    pub fn evaluate<T>(
        &self,
        mut bindings: impl FnMut(usize) -> T,
    ) -> Result<T, EvaluationError<O::Err>>
    where
        O: Operator<T>,
    {
        let mut stack = Vec::new();

        for element in self.elements.iter() {
            match element {
                Element::Variable(index) => stack.push(bindings(*index)),
                Element::Operator(op) => op
                    .execute(&mut stack)
                    .map_err(EvaluationError::OperatorFailed)?,
            }
        }

        match stack.pop() {
            Some(result) if stack.is_empty() => Ok(result),
            Some(_) => Err(EvaluationError::TooManyResults),
            None => Err(EvaluationError::NoResults),
        }
    }

    pub fn symbols(&self) -> &[String] {
        &self.symbols
    }

    pub fn formatted(&self) -> Result<String, EvaluationError<O::Err>>
    where
        O: Operator<Formatted>,
    {
        self.evaluate(|index| Formatted(self.symbols[index].clone()))
            .map(|formatted| formatted.0)
    }
}

#[derive(Clone, Debug)]
pub struct Formatted(pub String);

impl Display for Formatted {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl<O> Display for Expression<O>
where
    O: Operator<Formatted>,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.formatted() {
            Ok(result) => write!(f, "{}", result),
            Err(_) => write!(f, "<malformed expression>"),
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum Token<'a, O> {
    LBrace,
    RBrace,
    Operator(O),
    Variable(&'a str),
    Malformed(&'a str),
}

pub type Symbol<'a, O> = (&'a str, bool, Token<'a, O>);

#[derive(Debug)]
pub struct Tokens<'a, O> {
    source: &'a str,
    symbols: &'a [Symbol<'a, O>],
}

impl<'a, O> Tokens<'a, O> {
    pub fn new(source: &'a str, symbols: &'a [Symbol<'a, O>]) -> Self {
        Self { source, symbols }
    }
}

impl<'a, O: Clone> Iterator for Tokens<'a, O> {
    type Item = Token<'a, O>;

    fn next(&mut self) -> Option<Self::Item> {
        self.source = self.source.trim_start();

        let symbol = self.symbols.iter().find_map(|(symbol, word, token)| {
            if self.source.starts_with(symbol) {
                let end = symbol.len();

                if *word {
                    match &self.source[end..].chars().next() {
                        Some(c) if !c.is_whitespace() => return None,
                        _ => (),
                    }
                }

                Some((token, end))
            } else {
                None
            }
        });

        if let Some((token, end)) = symbol {
            self.source = &self.source[end..];
            Some(token.clone())
        } else {
            match self.source.chars().next() {
                Some(c) if c.is_alphabetic() => {
                    let end = self
                        .source
                        .char_indices()
                        .find_map(|(i, c)| Some(i).filter(|_| !c.is_alphanumeric()))
                        .unwrap_or_else(|| self.source.len());

                    let result = &self.source[0..end];
                    self.source = &self.source[end..];
                    Some(Token::Variable(result))
                }

                Some(c) => {
                    let end = c.len_utf8();
                    let result = &self.source[0..end];
                    self.source = &self.source[end..];
                    Some(Token::Malformed(result))
                }

                None => None,
            }
        }
    }
}

pub trait WithPriority {
    type Priority;

    fn priority(&self) -> Self::Priority;
}

impl<'a, O> FromIterator<Token<'a, O>> for Result<Expression<O>, Token<'a, O>>
where
    O: WithPriority,
    O::Priority: Ord,
{
    fn from_iter<T: IntoIterator<Item = Token<'a, O>>>(tokens: T) -> Self {
        let mut token_stack = Vec::new();
        let mut indices = HashMap::new();
        let mut symbols = Vec::new();
        let mut elements = Vec::new();

        'outer: for token in tokens {
            match token {
                Token::Malformed(_) => return Err(token),
                Token::LBrace => token_stack.push(token),
                Token::RBrace => {

                    while let Some(token) = token_stack.pop() {
                        match token {
                            Token::LBrace => continue 'outer,
                            Token::Operator(op) => elements.push(Element::Operator(op)),
                            _ => return Err(token),
                        }
                    }
                }

                Token::Variable(name) => {
                    let index = indices.len();
                    let symbol = name.to_string();
                    let index = *indices.entry(symbol.clone()).or_insert_with(|| {
                        symbols.push(symbol);
                        index
                    });

                    elements.push(Element::Variable(index));
                }

                Token::Operator(ref op) => {
                    while let Some(token) = token_stack.pop() {
                        match token {
                            Token::Operator(pop) if op.priority() < pop.priority() => {
                                elements.push(Element::Operator(pop));
                            }

                            Token::Operator(pop) => {
                                token_stack.push(Token::Operator(pop));
                                break;
                            }

                            _ => {
                                token_stack.push(token);
                                break;
                            }
                        }
                    }

                    token_stack.push(token);
                }
            }
        }

        while let Some(token) = token_stack.pop() {
            match token {
                Token::Operator(op) => elements.push(Element::Operator(op)),
                _ => return Err(token),
            }
        }

        Ok(Expression { elements, symbols })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Boolean {
    Or,
    Xor,
    And,
    Not,
}

impl Display for Boolean {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Or => "∨",
            Self::And => "∧",
            Self::Not => "¬",
            Self::Xor => "⩛",
        };

        write!(f, "{}", s)
    }
}

impl WithPriority for Boolean {
    type Priority = u8;

    fn priority(&self) -> u8 {
        match self {
            Self::Or => 0,
            Self::Xor => 1,
            Self::And => 2,
            Self::Not => 3,
        }
    }
}

#[derive(Clone, Debug)]
pub enum BooleanError {
    StackUnderflow,
}

impl Operator<bool> for Boolean {
    type Err = BooleanError;

    fn execute(&self, stack: &mut Vec<bool>) -> Result<(), Self::Err> {
        let mut pop = || stack.pop().ok_or(BooleanError::StackUnderflow);

        let result = match self {
            Boolean::Or => pop()? | pop()?,
            Boolean::And => pop()? & pop()?,
            Boolean::Xor => pop()? ^ pop()?,
            Boolean::Not => !pop()?,
        };

        stack.push(result);
        Ok(())
    }
}

impl Operator<Formatted> for Boolean {
    type Err = BooleanError;

    fn execute(&self, stack: &mut Vec<Formatted>) -> Result<(), Self::Err> {
        let mut pop = || stack.pop().ok_or(BooleanError::StackUnderflow);

        let result = match self {
            Boolean::Not => format!("{}{}", Boolean::Not, pop()?),

            binary_operator => {

                let b = pop()?;
                let a = pop()?;
                format!("({} {} {})", a, binary_operator, b)
            }
        };

        stack.push(Formatted(result));
        Ok(())
    }
}

impl Boolean {

    const SYMBOLS: [Symbol<'static, Boolean>; 18] = [
        ("(", false, Token::LBrace),
        (")", false, Token::RBrace),
        ("|", false, Token::Operator(Boolean::Or)),
        ("∨", false, Token::Operator(Boolean::Or)),
        ("or", true, Token::Operator(Boolean::Or)),
        ("OR", true, Token::Operator(Boolean::Or)),
        ("&", false, Token::Operator(Boolean::And)),
        ("∧", false, Token::Operator(Boolean::And)),
        ("and", true, Token::Operator(Boolean::And)),
        ("AND", true, Token::Operator(Boolean::And)),
        ("!", false, Token::Operator(Boolean::Not)),
        ("¬", false, Token::Operator(Boolean::Not)),
        ("not", true, Token::Operator(Boolean::Not)),
        ("NOT", true, Token::Operator(Boolean::Not)),
        ("^", false, Token::Operator(Boolean::Xor)),
        ("⩛", false, Token::Operator(Boolean::Xor)),
        ("xor", true, Token::Operator(Boolean::Xor)),
        ("XOR", true, Token::Operator(Boolean::Xor)),
    ];

    pub fn tokenize(s: &str) -> Tokens<'_, Boolean> {
        Tokens::new(s, &Self::SYMBOLS)
    }

    pub fn parse<'a>(s: &'a str) -> Result<Expression<Boolean>, Token<'a, Boolean>> {
        Self::tokenize(s).collect()
    }
}

fn print_truth_table(s: &str) -> Result<(), std::borrow::Cow<'_, str>> {
    let expression = Boolean::parse(s).map_err(|e| format!("Parsing failed at token {:?}", e))?;

    let formatted = expression
        .formatted()
        .map_err(|_| "Malformed expression detected.")?;

    let var_count = expression.symbols().len();
    if var_count > 64 {
        return Err("Too many variables to list.".into());
    }

    let column_widths = {

        let mut widths = Vec::with_capacity(var_count);

        for symbol in expression.symbols() {
            print!("{}  ", symbol);
            widths.push(symbol.chars().count() + 2);
        }

        println!("{}", formatted);
        let width = widths.iter().sum::<usize>() + formatted.chars().count();
        (0..width).for_each(|_| print!("-"));
        println!();

        widths
    };

    let var_value = |input, index| (input >> (var_count - 1 - index)) & 1 ^ 1;

    for var_values in 0u64..(1 << var_count) {
        for (var_index, width) in column_widths.iter().enumerate() {
            let value = var_value(var_values, var_index);
            print!("{:<width$}", value, width = width);
        }

        match expression.evaluate(|var_index| var_value(var_values, var_index) == 1) {
            Ok(result) => println!("{}", if result { "1" } else { "0" }),
            Err(e) => println!("{:?}", e),
        }
    }

    println!();
    Ok(())
}

fn main() {
    loop {
        let input = {
            println!("Enter the expression to parse (or nothing to quit):");
            let mut input = String::new();
            std::io::stdin().read_line(&mut input).unwrap();
            println!();
            input
        };

        if input.trim().is_empty() {
            break;
        }

        if let Err(e) = print_truth_table(&input) {
            eprintln!("{}\n", e);
        }
    }
}


Twin primes

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

bool isPrime(int64_t n) {
    int64_t i;

    if (n < 2)       return false;
    if (n % 2 == 0)  return n == 2;
    if (n % 3 == 0)  return n == 3;
    if (n % 5 == 0)  return n == 5;
    if (n % 7 == 0)  return n == 7;
    if (n % 11 == 0) return n == 11;
    if (n % 13 == 0) return n == 13;
    if (n % 17 == 0) return n == 17;
    if (n % 19 == 0) return n == 19;

    for (i = 23; i * i <= n; i += 2) {
        if (n % i == 0) return false;
    }

    return true;
}

int countTwinPrimes(int limit) {
    int count = 0;

    int64_t p3 = true, p2 = true, p1 = false;
    int64_t i;

    for (i = 5; i <= limit; i++) {
        p3 = p2;
        p2 = p1;
        p1 = isPrime(i);
        if (p3 && p1) {
            count++;
        }
    }
    return count;
}

void test(int limit) {
    int count = countTwinPrimes(limit);
    printf("Number of twin prime pairs less than %d is %d\n", limit, count);
}

int main() {
    test(10);
    test(100);
    test(1000);
    test(10000);
    test(100000);
    test(1000000);
    test(10000000);
    test(100000000);
    return 0;
}

use num_format::{Locale, ToFormattedString};

fn twin_prime_count_for_powers_of_ten(max_power: u32) {
    let mut count = 0;
    let mut previous = 0;
    let mut power = 1;
    let mut limit = 10;
    for prime in primal::Primes::all() {
        if prime > limit {
            println!(
                "Number of twin prime pairs less than {} is {}",
                limit.to_formatted_string(&Locale::en),
                count.to_formatted_string(&Locale::en)
            );
            limit *= 10;
            power += 1;
            if power > max_power {
                break;
            }
        }
        if previous > 0 && prime == previous + 2 {
            count += 1;
        }
        previous = prime;
    }
}

fn twin_prime_count(limit: usize) {
    let mut count = 0;
    let mut previous = 0;
    for prime in primal::Primes::all().take_while(|x| *x < limit) {
        if previous > 0 && prime == previous + 2 {
            count += 1;
        }
        previous = prime;
    }
    println!(
        "Number of twin prime pairs less than {} is {}",
        limit.to_formatted_string(&Locale::en),
        count.to_formatted_string(&Locale::en)
    );
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() > 1 {
        for i in 1..args.len() {
            if let Ok(limit) = args[i].parse::<usize>() {
                twin_prime_count(limit);
            } else {
                eprintln!("Cannot parse limit from string {}", args[i]);
            }
        }
    } else {
        twin_prime_count_for_powers_of_ten(10);
    }
}


Two sum

use std::cmp::Ordering;
use std::ops::Add;

fn two_sum<T>(arr: &[T], sum: T) -> Option<(usize, usize)>
where
    T: Add<Output = T> + Ord + Copy,
{
    if arr.len() == 0 {
        return None;
    }

    let mut i = 0;
    let mut j = arr.len() - 1;

    while i < j {
        match (arr[i] + arr[j]).cmp(&sum) {
            Ordering::Equal => return Some((i, j)),
            Ordering::Less => i += 1,
            Ordering::Greater => j -= 1,
        }
    }

    None
}

fn main() {
    let arr = [0, 2, 11, 19, 90];
    let sum = 21;

    println!("{:?}", two_sum(&arr, sum));
}


Type detection

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

void typeDetector(char* str){
	if(isalnum(str[0])!=0)
		printf("\n%c is alphanumeric",str[0]);
	if(isalpha(str[0])!=0)
		printf("\n%c is alphabetic",str[0]);
	if(iscntrl(str[0])!=0)
		printf("\n%c is a control character",str[0]);
	if(isdigit(str[0])!=0)
		printf("\n%c is a digit",str[0]);
	if(isprint(str[0])!=0)
		printf("\n%c is printable",str[0]);
	if(ispunct(str[0])!=0)
		printf("\n%c is a punctuation character",str[0]);
	if(isxdigit(str[0])!=0)
		printf("\n%c is a hexadecimal digit",str[0]);
}

int main(int argC, char* argV[])
{
	int i;

	if(argC==1)
		printf("Usage : %s <followed by ASCII characters>");
	else{
		for(i=1;i<argC;i++)
			typeDetector(argV[i]);
	}
	return 0;
}

enum ExpectedTypes {
    Int(i64),
    UInt(u64),
    Real(f64),
    Text(String),
    Uncertain,
}

use ExpectedTypes::*;

fn main() {
    let enum_test = &[Int(-5), UInt(10), Real(-15.5), Text("Twenty".to_owned()),
                     Uncertain];

    for entry in enum_test {
        match entry {
            Int(x) => println!("Got an integer: {}", x),
            UInt(x) => println!("Got an unsigned integer: {}", x),
            Real(x) => println!("Got a floating-point number: {}", x),
            Text(x) => println!("Got a string of text: {}", x),
            Uncertain => println!("Value is uncertain"),
        }
    }
}


URL encoding

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

char rfc3986[256] = {0};
char html5[256] = {0};

void encode(const char *s, char *enc, char *tb)
{
	for (; *s; s++) {
		if (tb[*s]) sprintf(enc, "%c", tb[*s]);
		else        sprintf(enc, "%%%02X", *s);
		while (*++enc);
	}
}

int main()
{
	const char url[] = "http:
	char enc[(strlen(url) * 3) + 1];

	int i;
	for (i = 0; i < 256; i++) {
		rfc3986[i] = isalnum(i)||i == '~'||i == '-'||i == '.'||i == '_'
			? i : 0;
		html5[i] = isalnum(i)||i == '*'||i == '-'||i == '.'||i == '_'
			? i : (i == ' ') ? '+' : 0;
	}

	encode(url, enc, rfc3986);
	puts(enc);

	return 0;
}

const INPUT: &str = "http:
const MAX_CHAR_VAL: u32 = std::char::MAX as u32;

fn main() {
    let mut buff = [0; 4];
    println!("{}", INPUT.chars()
        .map(|ch| {
            match ch as u32 {
                0 ..= 47 | 58 ..= 64 | 91 ..= 96 | 123 ..= MAX_CHAR_VAL => {
                    ch.encode_utf8(&mut buff);
                    buff[0..ch.len_utf8()].iter().map(|&byte| format!("%{:X}", byte)).collect::<String>()
                },
                _ => ch.to_string(),
            }
        })
        .collect::<String>()
    );
}


Ulam numbers

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

void fatal(const char* message) {
    fprintf(stderr, "%s\n", message);
    exit(1);
}

void* xmalloc(size_t n) {
    void* ptr = malloc(n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

void* xrealloc(void* p, size_t n) {
    void* ptr = realloc(p, n);
    if (ptr == NULL)
        fatal("Out of memory");
    return ptr;
}

int* extend(int* array, int min_length, int* capacity) {
    int new_capacity = *capacity;
    if (new_capacity >= min_length)
        return array;
    while (new_capacity < min_length)
        new_capacity *= 2;
    array = xrealloc(array, new_capacity * sizeof(int));
    memset(array + *capacity, 0, (new_capacity - *capacity) * sizeof(int));
    *capacity = new_capacity;
    return array;
}

int ulam(int n) {
    int* ulams = xmalloc((n < 2 ? 2 : n) * sizeof(int));
    ulams[0] = 1;
    ulams[1] = 2;
    int sieve_length = 2;
    int sieve_capacity = 2;
    int* sieve = xmalloc(sieve_capacity * sizeof(int));
    sieve[0] = sieve[1] = 1;
    for (int u = 2, ulen = 2; ulen < n; ) {
        sieve_length = u + ulams[ulen - 2];
        sieve = extend(sieve, sieve_length, &sieve_capacity);
        for (int i = 0; i < ulen - 1; ++i)
            ++sieve[u + ulams[i] - 1];
        for (int i = u; i < sieve_length; ++i) {
            if (sieve[i] == 1) {
                u = i + 1;
                ulams[ulen++] = u;
                break;
            }
        }
    }
    int result = ulams[n - 1];
    free(ulams);
    free(sieve);
    return result;
}

int main() {
    clock_t start = clock();
    for (int n = 1; n <= 100000; n *= 10)
        printf("Ulam(%d) = %d\n", n, ulam(n));
    clock_t finish = clock();
    printf("Elapsed time: %.3f seconds\n", (finish - start + 0.0)/CLOCKS_PER_SEC);
    return 0;
}

fn ulam(n: usize) -> usize {
    let mut ulams = vec![1, 2];
    let mut sieve = vec![1, 1];
    let mut u = 2;
    while ulams.len() < n {
        sieve.resize(u + ulams[ulams.len() - 2], 0);
        for i in 0..ulams.len() - 1 {
            sieve[u + ulams[i] - 1] += 1;
        }
        for i in u..sieve.len() {
            if sieve[i] == 1 {
                u = i + 1;
                ulams.push(u);
                break;
            }
        }
    }
    ulams[n - 1]
}

fn main() {
    use std::time::Instant;
    let start = Instant::now();
    let mut n = 1;
    while n <= 100000 {
        println!("Ulam({}) = {}", n, ulam(n));
        n *= 10;
    }
    println!("Elapsed time: {:.2?}", start.elapsed());
}


Unprimeable numbers

#include <assert.h>
#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct bit_array_tag {
    uint32_t size;
    uint32_t* array;
} bit_array;

bool bit_array_create(bit_array* b, uint32_t size) {
    uint32_t* array = calloc((size + 31)/32, sizeof(uint32_t));
    if (array == NULL)
        return false;
    b->size = size;
    b->array = array;
    return true;
}

void bit_array_destroy(bit_array* b) {
    free(b->array);
    b->array = NULL;
}

void bit_array_set(bit_array* b, uint32_t index, bool value) {
    assert(index < b->size);
    uint32_t* p = &b->array[index >> 5];
    uint32_t bit = 1 << (index & 31);
    if (value)
        *p |= bit;
    else
        *p &= ~bit;
}

bool bit_array_get(const bit_array* b, uint32_t index) {
    assert(index < b->size);
    uint32_t* p = &b->array[index >> 5];
    uint32_t bit = 1 << (index & 31);
    return (*p & bit) != 0;
}

typedef struct sieve_tag {
    uint32_t limit;
    bit_array not_prime;
} sieve;

bool sieve_create(sieve* s, uint32_t limit) {
    if (!bit_array_create(&s->not_prime, limit/2))
        return false;
    for (uint32_t p = 3; p * p <= limit; p += 2) {
        if (bit_array_get(&s->not_prime, p/2 - 1) == false) {
            uint32_t inc = 2 * p;
            for (uint32_t q = p * p; q <= limit; q += inc)
                bit_array_set(&s->not_prime, q/2 - 1, true);
        }
    }
    s->limit = limit;
    return true;
}

void sieve_destroy(sieve* s) {
    bit_array_destroy(&s->not_prime);
}

bool is_prime(const sieve* s, uint32_t n) {
    assert(n <= s->limit);
    if (n == 2)
        return true;
    if (n < 2 || n % 2 == 0)
        return false;
    return bit_array_get(&s->not_prime, n/2 - 1) == false;
}

uint32_t count_digits(uint32_t n) {
    uint32_t digits = 0;
    for (; n > 0; ++digits)
        n /= 10;
    return digits;
}

uint32_t change_digit(uint32_t n, uint32_t index, uint32_t new_digit) {
    uint32_t p = 1;
    uint32_t changed = 0;
    for (; index > 0; p *= 10, n /= 10, --index)
        changed += p * (n % 10);
    changed += (10 * (n/10) + new_digit) * p;
    return changed;
}

bool unprimeable(const sieve* s, uint32_t n) {
    if (is_prime(s, n))
        return false;
    uint32_t d = count_digits(n);
    for (uint32_t i = 0; i < d; ++i) {
        for (uint32_t j = 0; j <= 9; ++j) {
            uint32_t m = change_digit(n, i, j);
            if (m != n && is_prime(s, m))
                return false;
        }
    }
    return true;
}

int main() {
    const uint32_t limit = 10000000;
    setlocale(LC_ALL, "");
    sieve s = { 0 };
    if (!sieve_create(&s, limit)) {
        fprintf(stderr, "Out of memory\n");
        return 1;
    }
    printf("First 35 unprimeable numbers:\n");
    uint32_t n = 100;
    uint32_t lowest[10] = { 0 };
    for (uint32_t count = 0, found = 0; n < limit && (found < 10 || count < 600); ++n) {
        if (unprimeable(&s, n)) {
            if (count < 35) {
                if (count != 0)
                    printf(", ");
                printf("%'u", n);
            }
            ++count;
            if (count == 600)
                printf("\n600th unprimeable number: %'u\n", n);
            uint32_t last_digit = n % 10;
            if (lowest[last_digit] == 0) {
                lowest[last_digit] = n;
                ++found;
            }
        }
    }
    sieve_destroy(&s);
    for (uint32_t i = 0; i < 10; ++i)
        printf("Least unprimeable number ending in %u: %'u\n" , i, lowest[i]);
    return 0;
}

mod bit_array;
mod prime_sieve;

use prime_sieve::PrimeSieve;

fn count_digits(mut n: u32) -> u32 {
    let mut digits = 0;
    while n > 0 {
        n /= 10;
        digits += 1;
    }
    digits
}

fn change_digit(mut n: u32, mut index: u32, new_digit: u32) -> u32 {
    let mut p = 1;
    let mut changed = 0;
    while index > 0 {
        changed += p * (n % 10);
        p *= 10;
        n /= 10;
        index -= 1;
    }
    changed += (10 * (n / 10) + new_digit) * p;
    changed
}

fn unprimeable(sieve: &PrimeSieve, n: u32) -> bool {
    if sieve.is_prime(n as usize) {
        return false;
    }
    let d = count_digits(n);
    for i in 0..d {
        for j in 0..10 {
            let m = change_digit(n, i, j);
            if m != n && sieve.is_prime(m as usize) {
                return false;
            }
        }
    }
    true
}

fn main() {
    let mut count = 0;
    let mut n = 100;
    let mut lowest = vec![0; 10];
    let mut found = 0;
    let sieve = PrimeSieve::new(10000000);
    println!("First 35 unprimeable numbers:");
    while count < 600 || found < 10 {
        if unprimeable(&sieve, n) {
            if count < 35 {
                if count > 0 {
                    print!(", ");
                }
                print!("{}", n);
            }
            count += 1;
            if count == 600 {
                println!("\n600th unprimeable number: {}", n);
            }
            let last_digit = n as usize % 10;
            if lowest[last_digit] == 0 {
                lowest[last_digit] = n;
                found += 1;
            }
        }
        n += 1;
    }
    for i in 0..10 {
        println!("Least unprimeable number ending in {}: {}", i, lowest[i]);
    }
}


Vampire number

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <math.h>

typedef uint64_t xint;
typedef unsigned long long ull;

xint tens[20];

inline xint max(xint a, xint b) { return a > b ? a : b; }
inline xint min(xint a, xint b) { return a < b ? a : b; }
inline int ndigits(xint x)
{
	int n = 0;
	while (x) n++, x /= 10;
	return n;
}

inline xint dtally(xint x)
{
	xint t = 0;
	while (x) t += 1<<((x%10) * 6), x /= 10;

	return t;
}

int fangs(xint x, xint *f)
{
	int n = 0;
	int nd = ndigits(x);
	if (nd & 1) return 0;
	nd /= 2;

	xint lo, hi;
	lo = max(tens[nd-1], (x + tens[nd] - 2)/ (tens[nd] - 1));
	hi = min(x / lo, sqrt(x));

	xint a, b, t = dtally(x);
	for (a = lo; a <= hi; a++) {
		b = x / a;
		if (a * b == x && ((a%10) || (b%10)) && t == dtally(a) + dtally(b))
			f[n++] = a;
	}

	return n;
}

void show_fangs(xint x, xint *f, xint cnt)
{
	printf("%llu", (ull)x);
	int i;
	for (i = 0; i < cnt; i++)
		printf(" = %llu x %llu", (ull)f[i], (ull)(x / f[i]));
	putchar('\n');
}

int main(void)
{
	int i, j, n;
	xint x, f[16], bigs[] = {16758243290880ULL, 24959017348650ULL, 14593825548650ULL, 0};

	tens[0] = 1;
	for (i = 1; i < 20; i++)
		tens[i] = tens[i-1] * 10;

	for (x = 1, n = 0; n < 25; x++) {
		if (!(j = fangs(x, f))) continue;
		printf("%2d: ", ++n);
		show_fangs(x, f, j);
	}

	putchar('\n');
	for (i = 0; bigs[i]; i++) {
		if ((j = fangs(bigs[i], f)))
			show_fangs(bigs[i], f, j);
		else
			printf("%llu is not vampiric\n", (ull)bigs[i]);
	}

	return 0;
}


Vector

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

#define pi M_PI

typedef struct{
	double x,y;
}vector;

vector initVector(double r,double theta){
	vector c;

	c.x = r*cos(theta);
	c.y = r*sin(theta);

	return c;
}

vector addVector(vector a,vector b){
	vector c;

	c.x = a.x + b.x;
	c.y = a.y + b.y;

	return c;
}

vector subtractVector(vector a,vector b){
	vector c;

	c.x = a.x - b.x;
	c.y = a.y - b.y;

	return c;
}

vector multiplyVector(vector a,double b){
	vector c;

	c.x = b*a.x;
	c.y = b*a.y;

	return c;
}

vector divideVector(vector a,double b){
	vector c;

	c.x = a.x/b;
	c.y = a.y/b;

	return c;
}

void printVector(vector a){
	printf("%lf %c %c %lf %c",a.x,140,(a.y>=0)?'+':'-',(a.y>=0)?a.y:fabs(a.y),150);
}

int main()
{
	vector a = initVector(3,pi/6);
	vector b = initVector(5,2*pi/3);

	printf("\nVector a : ");
	printVector(a);

	printf("\n\nVector b : ");
	printVector(b);

	printf("\n\nSum of vectors a and b : ");
	printVector(addVector(a,b));

	printf("\n\nDifference of vectors a and b : ");
	printVector(subtractVector(a,b));

	printf("\n\nMultiplying vector a by 3 : ");
	printVector(multiplyVector(a,3));

	printf("\n\nDividing vector b by 2.5 : ");
	printVector(divideVector(b,2.5));

	return 0;
}

use std::fmt;
use std::ops::{Add, Div, Mul, Sub};

#[derive(Copy, Clone, Debug)]
pub struct Vector<T> {
    pub x: T,
    pub y: T,
}

impl<T> fmt::Display for Vector<T>
where
    T: fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(prec) = f.precision() {
            write!(f, "[{:.*}, {:.*}]", prec, self.x, prec, self.y)
        } else {
            write!(f, "[{}, {}]", self.x, self.y)
        }
    }
}

impl<T> Vector<T> {
    pub fn new(x: T, y: T) -> Self {
        Vector { x, y }
    }
}

impl Vector<f64> {
    pub fn from_polar(r: f64, theta: f64) -> Self {
        Vector {
            x: r * theta.cos(),
            y: r * theta.sin(),
        }
    }
}

impl<T> Add for Vector<T>
where
    T: Add<Output = T>,
{
    type Output = Self;

    fn add(self, other: Self) -> Self::Output {
        Vector {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

impl<T> Sub for Vector<T>
where
    T: Sub<Output = T>,
{
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        Vector {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

impl<T> Mul<T> for Vector<T>
where
    T: Mul<Output = T> + Copy,
{
    type Output = Self;

    fn mul(self, scalar: T) -> Self::Output {
        Vector {
            x: self.x * scalar,
            y: self.y * scalar,
        }
    }
}

impl<T> Div<T> for Vector<T>
where
    T: Div<Output = T> + Copy,
{
    type Output = Self;

    fn div(self, scalar: T) -> Self::Output {
        Vector {
            x: self.x / scalar,
            y: self.y / scalar,
        }
    }
}

fn main() {
    use std::f64::consts::FRAC_PI_3;

    println!("{:?}", Vector::new(4, 5));
    println!("{:.4}", Vector::from_polar(3.0, FRAC_PI_3));
    println!("{}", Vector::new(2, 3) + Vector::new(4, 6));
    println!("{:.4}", Vector::new(5.6, 1.3) - Vector::new(4.2, 6.1));
    println!("{:.4}", Vector::new(3.0, 4.2) * 2.3);
    println!("{:.4}", Vector::new(3.0, 4.2) / 2.3);
    println!("{}", Vector::new(3, 4) / 2);
}


Voronoi diagram

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N_SITES 150
double site[N_SITES][2];
unsigned char rgb[N_SITES][3];

int size_x = 640, size_y = 480;

inline double sq2(double x, double y)
{
	return x * x + y * y;
}

#define for_k for (k = 0; k < N_SITES; k++)
int nearest_site(double x, double y)
{
	int k, ret = 0;
	double d, dist = 0;
	for_k {
		d = sq2(x - site[k][0], y - site[k][1]);
		if (!k || d < dist) {
			dist = d, ret = k;
		}
	}
	return ret;
}

int at_edge(int *color, int y, int x)
{
	int i, j, c = color[y * size_x + x];
	for (i = y - 1; i <= y + 1; i++) {
		if (i < 0 || i >= size_y) continue;

		for (j = x - 1; j <= x + 1; j++) {
			if (j < 0 || j >= size_x) continue;
			if (color[i * size_x + j] != c) return 1;
		}
	}
	return 0;
}

#define AA_RES 4
void aa_color(unsigned char *pix, int y, int x)
{
	int i, j, n;
	double r = 0, g = 0, b = 0, xx, yy;
	for (i = 0; i < AA_RES; i++) {
		yy = y + 1. / AA_RES * i + .5;
		for (j = 0; j < AA_RES; j++) {
			xx = x + 1. / AA_RES * j + .5;
			n = nearest_site(xx, yy);
			r += rgb[n][0];
			g += rgb[n][1];
			b += rgb[n][2];
		}
	}
	pix[0] = r / (AA_RES * AA_RES);
	pix[1] = g / (AA_RES * AA_RES);
	pix[2] = b / (AA_RES * AA_RES);
}

#define for_i for (i = 0; i < size_y; i++)
#define for_j for (j = 0; j < size_x; j++)
void gen_map()
{
	int i, j, k;
	int *nearest = malloc(sizeof(int) * size_y * size_x);
	unsigned char *ptr, *buf, color;

	ptr = buf = malloc(3 * size_x * size_y);
	for_i for_j nearest[i * size_x + j] = nearest_site(j, i);

	for_i for_j {
		if (!at_edge(nearest, i, j))
			memcpy(ptr, rgb[nearest[i * size_x + j]], 3);
		else
			aa_color(ptr, i, j);
		ptr += 3;
	}

	for (k = 0; k < N_SITES; k++) {
		color = (rgb[k][0]*.25 + rgb[k][1]*.6 + rgb[k][2]*.15 > 80) ? 0 : 255;

		for (i = site[k][1] - 1; i <= site[k][1] + 1; i++) {
			if (i < 0 || i >= size_y) continue;

			for (j = site[k][0] - 1; j <= site[k][0] + 1; j++) {
				if (j < 0 || j >= size_x) continue;

				ptr = buf + 3 * (i * size_x + j);
				ptr[0] = ptr[1] = ptr[2] = color;
			}
		}
	}

	printf("P6\n%d %d\n255\n", size_x, size_y);
	fflush(stdout);
	fwrite(buf, size_y * size_x * 3, 1, stdout);
}

#define frand(x) (rand() / (1. + RAND_MAX) * x)
int main()
{
	int k;
	for_k {
		site[k][0] = frand(size_x);
		site[k][1] = frand(size_y);
		rgb [k][0] = frand(256);
		rgb [k][1] = frand(256);
		rgb [k][2] = frand(256);
	}

	gen_map();
	return 0;
}

extern crate piston;
extern crate opengl_graphics;
extern crate graphics;
extern crate touch_visualizer;

#[cfg(feature = "include_sdl2")]
extern crate sdl2_window;

extern crate getopts;
extern crate voronoi;
extern crate rand;

use touch_visualizer::TouchVisualizer;
use opengl_graphics::{ GlGraphics, OpenGL };
use graphics::{ Context, Graphics };
use piston::window::{ Window, WindowSettings };
use piston::input::*;
use piston::event_loop::*;
#[cfg(feature = "include_sdl2")]
use sdl2_window::Sdl2Window as AppWindow;
use voronoi::{voronoi, Point, make_polygons};
use rand::Rng;

static DEFAULT_WINDOW_HEIGHT: u32 = 600;
static DEFAULT_WINDOW_WIDTH:  u32 = 600;

struct Settings {
    lines_only: bool,
    random_count: usize
}

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let mut opts = getopts::Options::new();
    opts.optflag("l", "lines_only", "Don't color polygons, just outline them");
    opts.optopt("r", "random_count", "On keypress \"R\", put this many random points on-screen", "RANDOMCOUNT");
    let matches = opts.parse(&args[1..]).expect("Failed to parse args");

    let settings = Settings{
        lines_only: matches.opt_present("l"),
        random_count: match matches.opt_str("r") {
            None => { 50 },
            Some(s) => { s.parse().expect("Random count of bad format") }
        }
    };

    event_loop(&settings);

}

fn random_point() -> [f64; 2] {
    [rand::thread_rng().gen_range(0., DEFAULT_WINDOW_HEIGHT as f64), rand::thread_rng().gen_range(0., DEFAULT_WINDOW_WIDTH as f64)]
}

fn random_color() -> [f32; 4] {
    [rand::random::<f32>(), rand::random::<f32>(), rand::random::<f32>(), 1.0]
}

fn random_voronoi(dots: &mut Vec<[f64;2]>, colors: &mut Vec<[f32;4]>, num: usize) {
    dots.clear();
    colors.clear();

    for _ in 0..num {
        dots.push(random_point());
        colors.push(random_color());
    }
}

fn event_loop(settings: &Settings) {
    let opengl = OpenGL::V3_2;
    let mut window: AppWindow = WindowSettings::new("Interactive Voronoi", [DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH])
        .exit_on_esc(true).opengl(opengl).build().unwrap();

    let ref mut gl = GlGraphics::new(opengl);
    let mut touch_visualizer = TouchVisualizer::new();
    let mut events = Events::new(EventSettings::new().lazy(true));
    let mut dots = Vec::new();
    let mut colors = Vec::new();

    let mut mx = 0.0;
    let mut my = 0.0;

    while let Some(e) = events.next(&mut window) {
        touch_visualizer.event(window.size(), &e);
        if let Some(button) = e.release_args() {
            match button {
                Button::Keyboard(key) => {
                    if key == piston::input::keyboard::Key::N { dots.clear(); colors.clear(); }
                    if key == piston::input::keyboard::Key::R { random_voronoi(&mut dots, &mut colors, settings.random_count); }
                }
                Button::Mouse(_) => {
                    dots.push([mx, my]);
                    colors.push(random_color());
                },
                _ => ()
            }
        };
        e.mouse_cursor(|x, y| {
            mx = x;
            my = y;
        });
        if let Some(args) = e.render_args() {
            gl.draw(args.viewport(), |c, g| {
                graphics::clear([1.0; 4], g);
                let mut vor_pts = Vec::new();
                for d in &dots {
                    vor_pts.push(Point::new(d[0], d[1]));
                }
                if vor_pts.len() > 0 {
                    let vor_diagram = voronoi(vor_pts, DEFAULT_WINDOW_WIDTH as f64);
                    let vor_polys = make_polygons(&vor_diagram);
                    for (i, poly) in vor_polys.iter().enumerate() {
                        if settings.lines_only {
                            draw_lines_in_polygon(poly, &c, g);
                        } else {
                            draw_polygon(poly, &c, g, colors[i]);
                        }
                    }
                }
                for d in &dots {
                    draw_ellipse(&d, &c, g);
                }
            });
        }
    }

}

fn draw_lines_in_polygon<G: Graphics>(
    poly: &Vec<Point>,
    c: &Context,
    g: &mut G,
)
{
    let color = [0.0, 0.0, 1.0, 1.0];

    for i in 0..poly.len()-1 {
        graphics::line(
            color,
            2.0,
            [poly[i].x.into(), poly[i].y.into(), poly[i+1].x.into(), poly[i+1].y.into()],
            c.transform,
            g
        )
    }
}

fn draw_polygon<G: Graphics>(
    poly: &Vec<Point>,
    c: &Context,
    g: &mut G,
    color: [f32; 4]
) {
    let mut polygon_points: Vec<[f64; 2]> = Vec::new();

    for p in poly {
        polygon_points.push([p.x.into(), p.y.into()]);
    }

    graphics::polygon(
        color,
        polygon_points.as_slice(),
        c.transform,
        g
    )
}

fn draw_ellipse<G: Graphics>(
    cursor: &[f64; 2],
    c: &Context,
    g: &mut G,
) {
    let color = [0.0, 0.0, 0.0, 1.0];
    graphics::ellipse(
        color,
        graphics::ellipse::circle(cursor[0], cursor[1], 4.0),
        c.transform,
        g
    );
}


Wilson primes of order n

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <gmp.h>

bool *sieve(int limit) {
    int i, p;
    limit++;

    bool *c = calloc(limit, sizeof(bool));
    c[0] = true;
    c[1] = true;
    for (i = 4; i < limit; i += 2) c[i] = true;
    p = 3;
    while (true) {
        int p2 = p * p;
        if (p2 >= limit) break;
        for (i = p2; i < limit; i += 2 * p) c[i] = true;
        while (true) {
            p += 2;
            if (!c[p]) break;
        }
    }
    return c;
}

int main() {
    const int limit = 11000;
    int i, j, n, pc = 0;
    unsigned long p;
    bool *c = sieve(limit);
    for (i = 0; i < limit; ++i) {
        if (!c[i]) ++pc;
    }
    unsigned long *primes = (unsigned long *)malloc(pc * sizeof(unsigned long));
    for (i = 0, j = 0; i < limit; ++i) {
        if (!c[i]) primes[j++] = i;
    }
    mpz_t *facts = (mpz_t *)malloc(limit *sizeof(mpz_t));
    for (i = 0; i < limit; ++i) mpz_init(facts[i]);
    mpz_set_ui(facts[0], 1);
    for (i = 1; i < limit; ++i) mpz_mul_ui(facts[i], facts[i-1], i);
    mpz_t f, sign;
    mpz_init(f);
    mpz_init_set_ui(sign, 1);
    printf(" n:  Wilson primes\n");
    printf("--------------------\n");
    for (n = 1; n < 12; ++n) {
        printf("%2d:  ", n);
        mpz_neg(sign, sign);
        for (i = 0; i < pc; ++i) {
            p = primes[i];
            if (p < n) continue;
            mpz_mul(f, facts[n-1], facts[p-n]);
            mpz_sub(f, f, sign);
            if (mpz_divisible_ui_p(f, p*p)) printf("%ld ", p);
        }
        printf("\n");
    }
    free(c);
    free(primes);
    for (i = 0; i < limit; ++i) mpz_clear(facts[i]);
    free(facts);
    return 0;
}

use rug::Integer;

fn generate_primes(limit: usize) -> Vec<usize> {
    let mut sieve = vec![true; limit >> 1];
    let mut p = 3;
    let mut sq = p * p;
    while sq < limit {
        if sieve[p >> 1] {
            let mut q = sq;
            while q < limit {
                sieve[q >> 1] = false;
                q += p << 1;
            }
        }
        sq += (p + 1) << 2;
        p += 2;
    }
    let mut primes = Vec::new();
    if limit > 2 {
        primes.push(2);
    }
    for i in 1..sieve.len() {
        if sieve[i] {
            primes.push((i << 1) + 1);
        }
    }
    primes
}

fn factorials(limit: usize) -> Vec<Integer> {
    let mut f = vec![Integer::from(1)];
    let mut factorial = Integer::from(1);
    f.reserve(limit);
    for i in 1..limit {
        factorial *= i as u64;
        f.push(factorial.clone());
    }
    f
}

fn main() {
    let limit = 11000;
    let f = factorials(limit);
    let primes = generate_primes(limit);
    println!(" n | Wilson primes\n--------------------");
    let mut s = -1;
    for n in 1..=11 {
        print!("{:2} |", n);
        for p in &primes {
            if *p >= n {
                let mut num = Integer::from(&f[n - 1] * &f[*p - n]);
                num -= s;
                if num % ((p * p) as u64) == 0 {
                    print!(" {}", p);
                }
            }
        }
        println!();
        s = -s;
    }
}


Write to Windows event log

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

int main(int argC,char* argV[])
{
	char str[1000];

	if(argC!=5)
		printf("Usage : %s < Followed by level, id, source string and description>",argV[0]);
	else{
		sprintf(str,"EventCreate /t %s /id %s /l APPLICATION /so %s /d \"%s\"",argV[1],argV[2],argV[3],argV[4]);
		system(str);
	}

	return 0;
}

#[cfg(windows)]
mod bindings {
    ::windows::include_bindings!();
}

#[cfg(windows)]
use bindings::{
    Windows::Win32::Security::{
        GetTokenInformation, OpenProcessToken, PSID, TOKEN_ACCESS_MASK, TOKEN_INFORMATION_CLASS,
        TOKEN_USER,
    },
    Windows::Win32::SystemServices::{
        GetCurrentProcess, OpenEventLogA, ReportEventA, ReportEvent_wType, HANDLE, PSTR,
    },
};

#[cfg(windows)]
fn main() -> windows::Result<()> {
    let ph = unsafe { GetCurrentProcess() };
    let mut th: HANDLE = HANDLE(0);
    unsafe { OpenProcessToken(ph, TOKEN_ACCESS_MASK::TOKEN_QUERY, &mut th) }.ok()?;

    let mut length = 0_u32;
    unsafe {
        GetTokenInformation(
            th,
            TOKEN_INFORMATION_CLASS::TokenUser,
            std::ptr::null_mut(),
            0,
            &mut length,
        )
    }
    .ok()
    .unwrap_err();

    let mut token_user_bytes = vec![0u8; length as usize];
    unsafe {
        GetTokenInformation(
            th,
            TOKEN_INFORMATION_CLASS::TokenUser,
            token_user_bytes.as_mut_ptr().cast(),
            length,
            &mut length,
        )
    }
    .ok()?;

    let user_sid: PSID = unsafe { (*token_user_bytes.as_ptr().cast::<TOKEN_USER>()).User.Sid };

    let event_log_handle = unsafe { OpenEventLogA(PSTR::default(), "Application") };

    let mut event_msg = PSTR(b"Hello in the event log\0".as_ptr() as _);
    unsafe {
        ReportEventA(
            HANDLE(event_log_handle.0),
            ReportEvent_wType::EVENTLOG_WARNING_TYPE,
            5,
            1,
            user_sid,
            1,
            0,
            &mut event_msg,
            std::ptr::null_mut(),
        )
    }
    .ok()?;

    Ok(())
}

#[cfg(not(windows))]
fn main() {
    println!("Not implemented");
}


Y combinator

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

typedef struct func_t *func;
typedef struct func_t {
        func (*fn) (func, func);
        func _;
        int num;
} func_t;

func new(func(*f)(func, func), func _) {
        func x = malloc(sizeof(func_t));
        x->fn = f;
        x->_ = _;
        x->num = 0;
        return x;
}

func call(func f, func n) {
        return f->fn(f, n);
}

func Y(func(*f)(func, func)) {
        func g = new(f, 0);
        g->_ = g;
        return g;
}

func num(int n) {
        func x = new(0, 0);
        x->num = n;
        return x;
}

func fac(func self, func n) {
        int nn = n->num;
        return nn > 1   ? num(nn * call(self->_, num(nn - 1))->num)
                        : num(1);
}

func fib(func self, func n) {
        int nn = n->num;
        return nn > 1
                ? num(  call(self->_, num(nn - 1))->num +
                        call(self->_, num(nn - 2))->num )
                : num(1);
}

void show(func n) { printf(" %d", n->num); }

int main() {
        int i;
        func f = Y(fac);
        printf("fac: ");
        for (i = 1; i < 10; i++)
                show( call(f, num(i)) );
        printf("\n");

        f = Y(fib);
        printf("fib: ");
        for (i = 1; i < 10; i++)
                show( call(f, num(i)) );
        printf("\n");

        return 0;
}

trait Apply<T, R> {
    fn apply(&self, f: &dyn Apply<T, R>, t: T) -> R;
}

impl<T, R, F> Apply<T, R> for F where F: Fn(&dyn Apply<T, R>, T) -> R {
    fn apply(&self, f: &dyn Apply<T, R>, t: T) -> R {
        self(f, t)
    }
}

fn y<T, R>(f: impl Fn(&dyn Fn(T) -> R, T) -> R) -> impl Fn(T) -> R {
    move |t| (&|x: &dyn Apply<T, R>, y| x.apply(x, y))
             (&|x: &dyn Apply<T, R>, y| f(&|z| x.apply(x, z), y), t)
}

fn fac(n: usize) -> usize {
    let almost_fac = |f: &dyn Fn(usize) -> usize, x| if x == 0 { 1 } else { x * f(x - 1) };
    y(almost_fac)(n)
}

fn fib(n: usize) -> usize {
    let almost_fib = |f: &dyn Fn((usize, usize, usize)) -> usize, (a0, a1, x)|
        match x {
            0 => a0,
            1 => a1,
            _ => f((a1, a0 + a1, x - 1)),
        };

    y(almost_fib)((1, 1, n))
}

fn main() {
    let n = 10;
    println!("fac({}) = {}", n, fac(n));
    println!("fib({}) = {}", n, fib(n));
}