WeixiangYan/CodeTransOcean huggingface dataset:
Task: Humble numbers



C#: using System;
using System.Collections.Generic;

namespace HumbleNumbers {
    class Program {
        static bool IsHumble(int i) {
            if (i <= 1) return true;
            if (i % 2 == 0) return IsHumble(i / 2);
            if (i % 3 == 0) return IsHumble(i / 3);
            if (i % 5 == 0) return IsHumble(i / 5);
            if (i % 7 == 0) return IsHumble(i / 7);
            return false;
        }

        static void Main() {
            var limit = short.MaxValue;
            Dictionary<int, int> humble = new Dictionary<int, int>();
            var count = 0;
            var num = 1;

            while (count < limit) {
                if (IsHumble(num)) {
                    var str = num.ToString();
                    var len = str.Length;
                    if (humble.ContainsKey(len)) {
                        humble[len]++;
                    } else {
                        humble[len] = 1;
                    }
                    if (count < 50) Console.Write("{0} ", num);
                    count++;
                }
                num++;
            }
            Console.WriteLine("\n");

            Console.WriteLine("Of the first {0} humble numbers:", count);
            num = 1;
            while (num < humble.Count - 1) {
                if (humble.ContainsKey(num)) {
                    var c = humble[num];
                    Console.WriteLine("{0,5} have {1,2} digits", c, num);
                    num++;
                } else {
                    break;
                }
            }
        }
    }
}





Python: 

from itertools import groupby, islice
from functools import reduce



def humbles():
    
    hs = set([1])
    while True:
        nxt = min(hs)
        yield nxt
        hs.remove(nxt)
        hs.update(nxt * x for x in [2, 3, 5, 7])




def main():
    

    print('First 50 Humble numbers:\n')
    for row in chunksOf(10)(
            take(50)(humbles())
    ):
        print(' '.join(map(
            lambda x: str(x).rjust(3),
            row
        )))

    print('\nCounts of Humble numbers with n digits:\n')
    for tpl in take(10)(
            (k, len(list(g))) for k, g in
            groupby(len(str(x)) for x in humbles())
    ):
        print(tpl)





def chunksOf(n):
    
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []




def take(n):
    
    return lambda xs: (
        list(islice(xs, n))
    )



if __name__ == '__main__':
    main()
Task: Humble numbers




Go: package main

import (
    "fmt"
    "math/big"
)

var (
    one   = new(big.Int).SetUint64(1)
    two   = new(big.Int).SetUint64(2)
    three = new(big.Int).SetUint64(3)
    five  = new(big.Int).SetUint64(5)
    seven = new(big.Int).SetUint64(7)
    ten   = new(big.Int).SetUint64(10)
)

func min(a, b *big.Int) *big.Int {
    if a.Cmp(b) < 0 {
        return a
    }
    return b
}

func humble(n int) []*big.Int {
    h := make([]*big.Int, n)
    h[0] = new(big.Int).Set(one)
    next2, next3 := new(big.Int).Set(two), new(big.Int).Set(three)
    next5, next7 := new(big.Int).Set(five), new(big.Int).Set(seven)
    var i, j, k, l int
    for m := 1; m < len(h); m++ {
        h[m] = new(big.Int).Set(min(next2, min(next3, min(next5, next7))))
        if h[m].Cmp(next2) == 0 {
            i++
            next2.Mul(two, h[i])
        }
        if h[m].Cmp(next3) == 0 {
            j++
            next3.Mul(three, h[j])
        }
        if h[m].Cmp(next5) == 0 {
            k++
            next5.Mul(five, h[k])
        }
        if h[m].Cmp(next7) == 0 {
            l++
            next7.Mul(seven, h[l])
        }
    }
    return h
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    return s
}

func main() {
    const n = 13 * 1e6  
    h := humble(n) 
    fmt.Println("The first 50 humble numbers are:")
    fmt.Println(h[0:50])

    maxDigits := len(h[len(h)-1].String()) - 1
    counts := make([]int, maxDigits+1)
    var maxUsed int
    digits := 1
    pow10 := new(big.Int).Set(ten)
    for i := 0; i < len(h); i++ {
        for {
            if h[i].Cmp(pow10) >= 0 {
                pow10.Mul(pow10, ten)
                digits++
            } else {
                break
            }
        }  
        if digits > maxDigits {
            maxUsed = i
            break
        }
        counts[digits]++
    }
    fmt.Printf("\nOf the first %s humble numbers:\n", commatize(maxUsed))
    for i := 1; i <= maxDigits; i++ {
        s := "s"
        if i == 1 {
            s = ""
        }
        fmt.Printf("%9s have %2d digit%s\n", commatize(counts[i]), i, s)
    }       
}




Python: 

from itertools import groupby, islice
from functools import reduce



def humbles():
    
    hs = set([1])
    while True:
        nxt = min(hs)
        yield nxt
        hs.remove(nxt)
        hs.update(nxt * x for x in [2, 3, 5, 7])




def main():
    

    print('First 50 Humble numbers:\n')
    for row in chunksOf(10)(
            take(50)(humbles())
    ):
        print(' '.join(map(
            lambda x: str(x).rjust(3),
            row
        )))

    print('\nCounts of Humble numbers with n digits:\n')
    for tpl in take(10)(
            (k, len(list(g))) for k, g in
            groupby(len(str(x)) for x in humbles())
    ):
        print(tpl)





def chunksOf(n):
    
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []




def take(n):
    
    return lambda xs: (
        list(islice(xs, n))
    )



if __name__ == '__main__':
    main()
Task: Humble numbers







Python: 

from itertools import groupby, islice
from functools import reduce



def humbles():
    
    hs = set([1])
    while True:
        nxt = min(hs)
        yield nxt
        hs.remove(nxt)
        hs.update(nxt * x for x in [2, 3, 5, 7])




def main():
    

    print('First 50 Humble numbers:\n')
    for row in chunksOf(10)(
            take(50)(humbles())
    ):
        print(' '.join(map(
            lambda x: str(x).rjust(3),
            row
        )))

    print('\nCounts of Humble numbers with n digits:\n')
    for tpl in take(10)(
            (k, len(list(g))) for k, g in
            groupby(len(str(x)) for x in humbles())
    ):
        print(tpl)





def chunksOf(n):
    
    return lambda xs: reduce(
        lambda a, i: a + [xs[i:n + i]],
        range(0, len(xs), n), []
    ) if 0 < n else []




def take(n):
    
    return lambda xs: (
        list(islice(xs, n))
    )



if __name__ == '__main__':
    main()


VB: Module Module1

    Function IsHumble(i As Long) As Boolean
        If i <= 1 Then
            Return True
        End If
        If i Mod 2 = 0 Then
            Return IsHumble(i \ 2)
        End If
        If i Mod 3 = 0 Then
            Return IsHumble(i \ 3)
        End If
        If i Mod 5 = 0 Then
            Return IsHumble(i \ 5)
        End If
        If i Mod 7 = 0 Then
            Return IsHumble(i \ 7)
        End If
        Return False
    End Function

    Sub Main()
        Dim LIMIT = Short.MaxValue
        Dim humble As New Dictionary(Of Integer, Integer)
        Dim count = 0L
        Dim num = 1L

        While count < LIMIT
            If (IsHumble(num)) Then
                Dim str = num.ToString
                Dim len = str.Length
                If len > 10 Then
                    Exit While
                End If
                If humble.ContainsKey(len) Then
                    humble(len) += 1
                Else
                    humble(len) = 1
                End If
                If count < 50 Then
                    Console.Write("{0} ", num)
                End If
                count += 1
            End If
            num += 1
        End While
        Console.WriteLine(vbNewLine)

        Console.WriteLine("Of the first {0} humble numbers:", count)
        num = 1
        While num < humble.Count
            If humble.ContainsKey(num) Then
                Dim c = humble(num)
                Console.WriteLine("{0,5} have {1,2} digits", c, num)
                num += 1
            Else
                Exit While
            End If
        End While
    End Sub

End Module
Task: Humble numbers

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

bool isHumble(int i) {
    if (i <= 1) return true;
    if (i % 2 == 0) return isHumble(i / 2);
    if (i % 3 == 0) return isHumble(i / 3);
    if (i % 5 == 0) return isHumble(i / 5);
    if (i % 7 == 0) return isHumble(i / 7);
    return false;
}

int main() {
    int limit = SHRT_MAX;
    int humble[16];
    int count = 0;
    int num = 1;
    char buffer[16];

    memset(humble, 0, sizeof(humble));

    for (; count < limit; num++) {
        if (isHumble(num)) {
            size_t len;
            sprintf_s(buffer, sizeof(buffer), "%d", num);
            len = strlen(buffer);
            if (len >= 16) {
                break;
            }
            humble[len]++;

            if (count < 50) {
                printf("%d ", num);
            }
            count++;
        }
    }
    printf("\n\n");

    printf("Of the first %d humble numbers:\n", count);
    for (num = 1; num < 10; num++) {
        printf("%5d have %d digits\n", humble[num], num);
    }

    return 0;
}



C#: using System;
using System.Collections.Generic;

namespace HumbleNumbers {
    class Program {
        static bool IsHumble(int i) {
            if (i <= 1) return true;
            if (i % 2 == 0) return IsHumble(i / 2);
            if (i % 3 == 0) return IsHumble(i / 3);
            if (i % 5 == 0) return IsHumble(i / 5);
            if (i % 7 == 0) return IsHumble(i / 7);
            return false;
        }

        static void Main() {
            var limit = short.MaxValue;
            Dictionary<int, int> humble = new Dictionary<int, int>();
            var count = 0;
            var num = 1;

            while (count < limit) {
                if (IsHumble(num)) {
                    var str = num.ToString();
                    var len = str.Length;
                    if (humble.ContainsKey(len)) {
                        humble[len]++;
                    } else {
                        humble[len] = 1;
                    }
                    if (count < 50) Console.Write("{0} ", num);
                    count++;
                }
                num++;
            }
            Console.WriteLine("\n");

            Console.WriteLine("Of the first {0} humble numbers:", count);
            num = 1;
            while (num < humble.Count - 1) {
                if (humble.ContainsKey(num)) {
                    var c = humble[num];
                    Console.WriteLine("{0,5} have {1,2} digits", c, num);
                    num++;
                } else {
                    break;
                }
            }
        }
    }
}
Task: Humble numbers


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

bool isHumble(int i) {
    if (i <= 1) return true;
    if (i % 2 == 0) return isHumble(i / 2);
    if (i % 3 == 0) return isHumble(i / 3);
    if (i % 5 == 0) return isHumble(i / 5);
    if (i % 7 == 0) return isHumble(i / 7);
    return false;
}

auto toString(int n) {
    std::stringstream ss;
    ss << n;
    return ss.str();
}

int main() {
    auto limit = SHRT_MAX;
    std::map<int, int> humble;
    auto count = 0;
    auto num = 1;

    while (count < limit) {
        if (isHumble(num)) {
            auto str = toString(num);
            auto len = str.length();
            auto it = humble.find(len);

            if (it != humble.end()) {
                it->second++;
            } else {
                humble[len] = 1;
            }

            if (count < 50) std::cout << num << ' ';
            count++;
        }
        num++;
    }
    std::cout << "\n\n";

    std::cout << "Of the first " << count << " humble numbers:\n";
    num = 1;
    while (num < humble.size() - 1) {
        auto it = humble.find(num);
        if (it != humble.end()) {
            auto c = *it;
            std::cout << std::setw(5) << c.second << " have " << std::setw(2) << num << " digits\n";
            num++;
        } else {
            break;
        }
    }

    return 0;
}


C#: using System;
using System.Collections.Generic;

namespace HumbleNumbers {
    class Program {
        static bool IsHumble(int i) {
            if (i <= 1) return true;
            if (i % 2 == 0) return IsHumble(i / 2);
            if (i % 3 == 0) return IsHumble(i / 3);
            if (i % 5 == 0) return IsHumble(i / 5);
            if (i % 7 == 0) return IsHumble(i / 7);
            return false;
        }

        static void Main() {
            var limit = short.MaxValue;
            Dictionary<int, int> humble = new Dictionary<int, int>();
            var count = 0;
            var num = 1;

            while (count < limit) {
                if (IsHumble(num)) {
                    var str = num.ToString();
                    var len = str.Length;
                    if (humble.ContainsKey(len)) {
                        humble[len]++;
                    } else {
                        humble[len] = 1;
                    }
                    if (count < 50) Console.Write("{0} ", num);
                    count++;
                }
                num++;
            }
            Console.WriteLine("\n");

            Console.WriteLine("Of the first {0} humble numbers:", count);
            num = 1;
            while (num < humble.Count - 1) {
                if (humble.ContainsKey(num)) {
                    var c = humble[num];
                    Console.WriteLine("{0,5} have {1,2} digits", c, num);
                    num++;
                } else {
                    break;
                }
            }
        }
    }
}
Task: Humble numbers


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

bool isHumble(int i) {
    if (i <= 1) return true;
    if (i % 2 == 0) return isHumble(i / 2);
    if (i % 3 == 0) return isHumble(i / 3);
    if (i % 5 == 0) return isHumble(i / 5);
    if (i % 7 == 0) return isHumble(i / 7);
    return false;
}

auto toString(int n) {
    std::stringstream ss;
    ss << n;
    return ss.str();
}

int main() {
    auto limit = SHRT_MAX;
    std::map<int, int> humble;
    auto count = 0;
    auto num = 1;

    while (count < limit) {
        if (isHumble(num)) {
            auto str = toString(num);
            auto len = str.length();
            auto it = humble.find(len);

            if (it != humble.end()) {
                it->second++;
            } else {
                humble[len] = 1;
            }

            if (count < 50) std::cout << num << ' ';
            count++;
        }
        num++;
    }
    std::cout << "\n\n";

    std::cout << "Of the first " << count << " humble numbers:\n";
    num = 1;
    while (num < humble.size() - 1) {
        auto it = humble.find(num);
        if (it != humble.end()) {
            auto c = *it;
            std::cout << std::setw(5) << c.second << " have " << std::setw(2) << num << " digits\n";
            num++;
        } else {
            break;
        }
    }

    return 0;
}







VB: Module Module1

    Function IsHumble(i As Long) As Boolean
        If i <= 1 Then
            Return True
        End If
        If i Mod 2 = 0 Then
            Return IsHumble(i \ 2)
        End If
        If i Mod 3 = 0 Then
            Return IsHumble(i \ 3)
        End If
        If i Mod 5 = 0 Then
            Return IsHumble(i \ 5)
        End If
        If i Mod 7 = 0 Then
            Return IsHumble(i \ 7)
        End If
        Return False
    End Function

    Sub Main()
        Dim LIMIT = Short.MaxValue
        Dim humble As New Dictionary(Of Integer, Integer)
        Dim count = 0L
        Dim num = 1L

        While count < LIMIT
            If (IsHumble(num)) Then
                Dim str = num.ToString
                Dim len = str.Length
                If len > 10 Then
                    Exit While
                End If
                If humble.ContainsKey(len) Then
                    humble(len) += 1
                Else
                    humble(len) = 1
                End If
                If count < 50 Then
                    Console.Write("{0} ", num)
                End If
                count += 1
            End If
            num += 1
        End While
        Console.WriteLine(vbNewLine)

        Console.WriteLine("Of the first {0} humble numbers:", count)
        num = 1
        While num < humble.Count
            If humble.ContainsKey(num) Then
                Dim c = humble(num)
                Console.WriteLine("{0,5} have {1,2} digits", c, num)
                num += 1
            Else
                Exit While
            End If
        End While
    End Sub

End Module
Task: Ulam spiral (for primes)

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

typedef uint32_t bitsieve;

unsigned sieve_check(bitsieve *b, const unsigned v)
{
    if ((v != 2 && !(v & 1)) || (v < 2))
        return 0;
    else
        return !(b[v >> 6] & (1 << (v >> 1 & 31)));
}

bitsieve* sieve(const unsigned v)
{
    unsigned i, j;
    bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t));

    for (i = 3; i <= sqrt(v); i += 2)
        if (!(b[i >> 6] & (1 << (i >> 1 & 31))))
            for (j = i*i; j < v; j += (i << 1))
                b[j >> 6] |= (1 << (j >> 1 & 31));

    return b;
}

#define max(x,y) ((x) > (y) ? (x) : (y))


int ulam_get_map(int x, int y, int n)
{
    x -= (n - 1) / 2;
    y -= n / 2;

    int mx = abs(x), my = abs(y);
    int l = 2 * max(mx, my);
    int d = y >= x ? l * 3 + x + y : l - x - y;

    return pow(l - 1, 2) + d;
}


void output_ulam_spiral(int n, const char glyph)
{
    
    n -= n % 2 == 0 ? 1 : 0;

    const char *spaces = ".................";
    int mwidth = log10(n * n) + 1;

    bitsieve *b = sieve(n * n + 1);
    int x, y;

    for (x = 0; x < n; ++x) {
        for (y = 0; y < n; ++y) {
            int z = ulam_get_map(y, x, n);

            if (glyph == 0) {
                if (sieve_check(b, z))
                    printf("%*d ", mwidth, z);
                else
                    printf("%.*s ", mwidth, spaces);
            }
            else {
                printf("%c", sieve_check(b, z) ? glyph : spaces[0]);
            }
        }
        printf("\n");
    }

    free(b);
}

int main(int argc, char *argv[])
{
    const int n = argc < 2 ? 9 : atoi(argv[1]);

    output_ulam_spiral(n, 0);
    printf("\n");

    output_ulam_spiral(n, '#');
    printf("\n");

    return 0;
}




Go: package main

import (
	"math"
	"fmt"
)

type Direction byte

const (
	RIGHT Direction = iota
	UP
	LEFT
	DOWN
)

func generate(n,i int, c byte) {
	s := make([][]string, n)
	for i := 0; i < n; i++ { s[i] = make([]string, n) }
	dir := RIGHT
	y := n / 2
	var x int
	if (n % 2 == 0) { x = y - 1 } else { x = y } 

	for j := i; j <= n * n - 1 + i; j++ {
		if (isPrime(j)) {
			if (c == 0) { s[y][x] = fmt.Sprintf("%3d", j) } else { s[y][x] = fmt.Sprintf("%2c ", c) }
		} else { s[y][x] = "---" }

		switch dir {
		case RIGHT : if (x <= n - 1 && s[y - 1][x] == "" && j > i) { dir = UP }
		case UP : if (s[y][x - 1] == "") { dir = LEFT }
		case LEFT : if (x == 0 || s[y + 1][x] == "") { dir = DOWN }
		case DOWN : if (s[y][x + 1] == "") { dir = RIGHT }
		}

		switch dir {
		case RIGHT : x += 1
		case UP : y -= 1
		case LEFT : x -= 1
		case DOWN : y += 1
		}
	}

	for _, row := range s { fmt.Println(fmt.Sprintf("%v", row)) }
	fmt.Println()
}

func isPrime(a int) bool {
	if (a == 2) { return true }
	if (a <= 1 || a % 2 == 0) { return false }
	max := int(math.Sqrt(float64(a)))
	for n := 3; n <= max; n += 2 { if (a % n == 0) { return false } }
	return true
}

func main() {
	generate(9, 1, 0) 
	generate(9, 1, '*') 
}
Task: Ulam spiral (for primes)

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

typedef uint32_t bitsieve;

unsigned sieve_check(bitsieve *b, const unsigned v)
{
    if ((v != 2 && !(v & 1)) || (v < 2))
        return 0;
    else
        return !(b[v >> 6] & (1 << (v >> 1 & 31)));
}

bitsieve* sieve(const unsigned v)
{
    unsigned i, j;
    bitsieve *b = calloc((v >> 6) + 1, sizeof(uint32_t));

    for (i = 3; i <= sqrt(v); i += 2)
        if (!(b[i >> 6] & (1 << (i >> 1 & 31))))
            for (j = i*i; j < v; j += (i << 1))
                b[j >> 6] |= (1 << (j >> 1 & 31));

    return b;
}

#define max(x,y) ((x) > (y) ? (x) : (y))


int ulam_get_map(int x, int y, int n)
{
    x -= (n - 1) / 2;
    y -= n / 2;

    int mx = abs(x), my = abs(y);
    int l = 2 * max(mx, my);
    int d = y >= x ? l * 3 + x + y : l - x - y;

    return pow(l - 1, 2) + d;
}


void output_ulam_spiral(int n, const char glyph)
{
    
    n -= n % 2 == 0 ? 1 : 0;

    const char *spaces = ".................";
    int mwidth = log10(n * n) + 1;

    bitsieve *b = sieve(n * n + 1);
    int x, y;

    for (x = 0; x < n; ++x) {
        for (y = 0; y < n; ++y) {
            int z = ulam_get_map(y, x, n);

            if (glyph == 0) {
                if (sieve_check(b, z))
                    printf("%*d ", mwidth, z);
                else
                    printf("%.*s ", mwidth, spaces);
            }
            else {
                printf("%c", sieve_check(b, z) ? glyph : spaces[0]);
            }
        }
        printf("\n");
    }

    free(b);
}

int main(int argc, char *argv[])
{
    const int n = argc < 2 ? 9 : atoi(argv[1]);

    output_ulam_spiral(n, 0);
    printf("\n");

    output_ulam_spiral(n, '#');
    printf("\n");

    return 0;
}







Python: 
from __future__ import print_function, division
from math import sqrt

def cell(n, x, y, start=1):
    d, y, x = 0, y - n//2, x - (n - 1)//2
    l = 2*max(abs(x), abs(y))
    d = (l*3 + x + y) if y >= x else (l - x - y)
    return (l - 1)**2 + d + start - 1

def show_spiral(n, symbol='
    top = start + n*n + 1
    is_prime = [False,False,True] + [True,False]*(top//2)
    for x in range(3, 1 + int(sqrt(top))):
        if not is_prime[x]: continue
        for i in range(x*x, top, x*2):
            is_prime[i] = False

    cell_str = lambda x: f(x) if is_prime[x] else space
    f = lambda _: symbol 

    if space == None: space = ' '*len(symbol)

    if not len(symbol): 
        max_str = len(str(n*n + start - 1))
        if space == None: space = '.'*max_str + ' '
        f = lambda x: ('%' + str(max_str) + 'd ')%x

    for y in range(n):
        print(''.join(cell_str(v) for v in [cell(n, x, y, start) for x in range(n)]))
    print()

show_spiral(10, symbol=u'♞', space=u'♘') 
show_spiral(9, symbol='', space=' - ')