WeixiangYan/CodeTransOcean huggingface dataset:
Task: Legendre prime counting function





Java: import java.util.*;

public class LegendrePrimeCounter {
    public static void main(String[] args) {
        LegendrePrimeCounter counter = new LegendrePrimeCounter(1000000000);
        for (int i = 0, n = 1; i < 10; ++i, n *= 10)
            System.out.printf("10^%d\t%d\n", i, counter.primeCount((n)));
    }

    private List<Integer> primes;

    public LegendrePrimeCounter(int limit) {
        primes = generatePrimes((int)Math.sqrt((double)limit));
    }

    public int primeCount(int n) {
        if (n < 2)
            return 0;
        int a = primeCount((int)Math.sqrt((double)n));
        return phi(n, a) + a - 1;
    }

    private int phi(int x, int a) {
        if (a == 0)
            return x;
        if (a == 1)
            return x - (x >> 1);
        int pa = primes.get(a - 1);
        if (x <= pa)
            return 1;
        return phi(x, a - 1) - phi(x / pa, a - 1);
    }

    private static List<Integer> generatePrimes(int limit) {
        boolean[] sieve = new boolean[limit >> 1];
        Arrays.fill(sieve, true);
        for (int p = 3, s = 9; s < limit; p += 2) {
            if (sieve[p >> 1]) {
                for (int q = s; q < limit; q += p << 1)
                    sieve[q >> 1] = false;
            }
            s += (p + 1) << 2;
        }
        List<Integer> primes = new ArrayList<>();
        if (limit > 2)
            primes.add(2);
        for (int i = 1; i < sieve.length; ++i) {
            if (sieve[i])
                primes.add((i << 1) + 1);
        } 
        return primes;
    }
}



Python: from primesieve import primes
from math import isqrt
from functools import cache

p = primes(isqrt(1_000_000_000))

@cache
def phi(x, a):
    res = 0
    while True:
        if not a or not x:
            return x + res
    
        a -= 1
        res -= phi(x//p[a], a) 

def legpi(n):
    if n < 2: return 0

    a = legpi(isqrt(n))
    return phi(n, a) + a - 1

for e in range(10):
    print(f'10^{e}', legpi(10**e))
Task: Use another language to call a function





Java: 
public class Query {
    public static boolean call(byte[] data, int[] length)
	throws java.io.UnsupportedEncodingException
    {
	String message = "Here am I";
	byte[] mb = message.getBytes("utf-8");
	if (length[0] < mb.length)
	    return false;
	length[0] = mb.length;
	System.arraycopy(mb, 0, data, 0, mb.length);
	return true;
    }
}



Python: 

def query(buffer_length):
    message = b'Here am I'
    L = len(message)
    return message[0:L*(L <= buffer_length)]
Task: Longest string challenge





Java: import java.io.File;
import java.util.Scanner;

public class LongestStringChallenge {

    public static void main(String[] args) throws Exception {
        String lines = "", longest = "";
        try (Scanner sc = new Scanner(new File("lines.txt"))) {
            while(sc.hasNext()) {
                String line = sc.nextLine();
                if (longer(longest, line))
                    lines = longest = line;
                else if (!longer(line, longest))
                    lines = lines.concat("\n").concat(line);
            }
        }
        System.out.println(lines);
    }

    static boolean longer(String a, String b) {
        try {
            String dummy = a.substring(b.length());
        } catch (StringIndexOutOfBoundsException e) {
            return true;
        }
        return false;
    }
}



Python: import fileinput






def longer(a, b):
    try:
        b[len(a)-1]
        return False
    except:
        return True

longest, lines = '', ''
for x in fileinput.input():
    if longer(x, longest):
        lines, longest = x, x
    elif not longer(longest, x):
        lines += x

print(lines, end='')
Task: Create a file





Java: import java.io.*;
public class CreateFileTest {
	public static void main(String args[]) {
		try {
			new File("output.txt").createNewFile();
			new File(File.separator + "output.txt").createNewFile();
			new File("docs").mkdir();
			new File(File.separator + "docs").mkdir();
		} catch (IOException e) {
			System.err.println(e.getMessage());
		}
	}
}



Python: import os
for directory in ['/', './']:
  open(directory + 'output.txt', 'w').close()  
  os.mkdir(directory + 'docs')
Task: Tau function





Java: public class TauFunction {
    private static long divisorCount(long n) {
        long total = 1;
        
        for (; (n & 1) == 0; n >>= 1) {
            ++total;
        }
        
        for (long p = 3; p * p <= n; p += 2) {
            long count = 1;
            for (; n % p == 0; n /= p) {
                ++count;
            }
            total *= count;
        }
        
        if (n > 1) {
            total *= 2;
        }
        return total;
    }

    public static void main(String[] args) {
        final int limit = 100;
        System.out.printf("Count of divisors for the first %d positive integers:\n", limit);
        for (long n = 1; n <= limit; ++n) {
            System.out.printf("%3d", divisorCount(n));
            if (n % 20 == 0) {
                System.out.println();
            }
        }
    }
}



Python: def factorize(n):
    assert(isinstance(n, int))
    if n < 0: 
        n = -n 
    if n < 2: 
        return 
    k = 0 
    while 0 == n%2: 
        k += 1 
        n //= 2 
    if 0 < k: 
        yield (2,k) 
    p = 3 
    while p*p <= n: 
        k = 0 
        while 0 == n%p: 
            k += 1 
            n //= p 
        if 0 < k: 
            yield (p,k)
        p += 2 
    if 1 < n: 
        yield (n,1) 

def tau(n): 
    assert(n != 0) 
    ans = 1 
    for (p,k) in factorize(n): 
        ans *= 1 + k
    return ans

if __name__ == "__main__":
    print(*map(tau, range(1, 101)))
Task: Sequence of primorial primes





Java: import java.math.BigInteger;

public class PrimorialPrimes {

    final static int sieveLimit = 1550_000;
    static boolean[] notPrime = sieve(sieveLimit);

    public static void main(String[] args) {

        int count = 0;
        for (int i = 1; i < 1000_000 && count < 20; i++) {
            BigInteger b = primorial(i);
            if (b.add(BigInteger.ONE).isProbablePrime(1)
                    || b.subtract(BigInteger.ONE).isProbablePrime(1)) {
                System.out.printf("%d ", i);
                count++;
            }
        }
    }

    static BigInteger primorial(int n) {
        if (n == 0)
            return BigInteger.ONE;

        BigInteger result = BigInteger.ONE;
        for (int i = 0; i < sieveLimit && n > 0; i++) {
            if (notPrime[i])
                continue;
            result = result.multiply(BigInteger.valueOf(i));
            n--;
        }
        return result;
    }

    public static boolean[] sieve(int limit) {
        boolean[] composite = new boolean[limit];
        composite[0] = composite[1] = true;

        int max = (int) Math.sqrt(limit);
        for (int n = 2; n <= max; n++) {
            if (!composite[n]) {
                for (int k = n * n; k < limit; k += n) {
                    composite[k] = true;
                }
            }
        }
        return composite;
    }
}



Python: import pyprimes

def primorial_prime(_pmax=500):
    isprime = pyprimes.isprime
    n, primo = 0, 1
    for prime in pyprimes.nprimes(_pmax):
        n, primo = n+1, primo * prime
        if isprime(primo-1) or isprime(primo+1):
            yield n
        
if __name__ == '__main__':
    
    pyprimes.warn_probably = False  
    for i, n in zip(range(20), primorial_prime()):
        print('Primorial prime %2i at primorial index: %3i' % (i+1, n))
Task: Bioinformatics_base count





Java: import java.util.HashMap;
import java.util.Map;

public class orderedSequence {
    public static void main(String[] args) {
        Sequence gene = new Sequence("CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT");
        gene.runSequence();
    }
}


public class Sequence {
    
    private final String seq;
    
    public Sequence(String sq) {
        this.seq = sq;
    }
    
    
    public void prettyPrint() {
        System.out.println("Sequence:");
        int i = 0;
        for ( ; i < seq.length() - 50 ; i += 50) {
            System.out.printf("%5s : %s\n", i + 50, seq.substring(i, i + 50));
        }
        System.out.printf("%5s : %s\n", seq.length(), seq.substring(i));
    }
    
    
    public void displayCount() {
        Map<Character, Integer> counter = new HashMap<>();
        for (int i = 0 ; i < seq.length() ; ++i) {
            counter.merge(seq.charAt(i), 1, Integer::sum);
        }

        System.out.println("Base vs. Count:");
        counter.forEach(
            key, value -> System.out.printf("%5s : %s\n", key, value));
        System.out.printf("%5s: %s\n", "SUM", seq.length());
    }
    
    public void runSequence() {
        this.prettyPrint();
        this.displayCount();
    }
}



Python: from collections import Counter

def basecount(dna):
    return sorted(Counter(dna).items())

def seq_split(dna, n=50):
    return [dna[i: i+n] for i in range(0, len(dna), n)]

def seq_pp(dna, n=50):
    for i, part in enumerate(seq_split(dna, n)):
        print(f"{i*n:>5}: {part}")
    print("\n  BASECOUNT:")
    tot = 0
    for base, count in basecount(dna):
        print(f"    {base:>3}: {count}")
        tot += count
    base, count = 'TOT', tot
    print(f"    {base:>3}= {count}")
    
if __name__ == '__main__':
    print("SEQUENCE:")
    sequence = 
    seq_pp(sequence)
Task: Factorions





Java: public class Factorion {
    public static void main(String [] args){
        System.out.println("Base 9:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,9);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
        System.out.println("\nBase 10:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,10);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
        System.out.println("\nBase 11:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,11);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
        System.out.println("\nBase 12:");
        for(int i = 1; i <= 1499999; i++){
            String iStri = String.valueOf(i);
            int multiplied = operate(iStri,12);
            if(multiplied == i){
                System.out.print(i + "\t");
            }
        }
    }
    public static int factorialRec(int n){
        int result = 1;
        return n == 0 ? result : result * n * factorialRec(n-1);
    }

    public static int operate(String s, int base){
        int sum = 0;
        String strx = fromDeci(base, Integer.parseInt(s));
        for(int i = 0; i < strx.length(); i++){
            if(strx.charAt(i) == 'A'){
                sum += factorialRec(10);
            }else if(strx.charAt(i) == 'B') {
                sum += factorialRec(11);
            }else if(strx.charAt(i) == 'C') {
                sum += factorialRec(12);
            }else {
                sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base));
            }
        }
        return sum;
    }
    
    static char reVal(int num) {
        if (num >= 0 && num <= 9)
            return (char)(num + 48);
        else
            return (char)(num - 10 + 65);
    }
    static String fromDeci(int base, int num){
        StringBuilder s = new StringBuilder();
        while (num > 0) {
            s.append(reVal(num % base));
            num /= base;
        }
        return new String(new StringBuilder(s).reverse());
    }
}



Python: fact = [1] 
for n in range(1, 12):
    fact.append(fact[n-1] * n)

for b in range(9, 12+1):
    print(f"The factorions for base {b} are:")
    for i in range(1, 1500000):
        fact_sum = 0
        j = i
        while j > 0:
            d = j % b
            fact_sum += fact[d]
            j = j//b
        if fact_sum == i:
            print(i, end=" ")
    print("\n")
Task: Sorting algorithms_Strand sort





Java: import java.util.Arrays;
import java.util.LinkedList;

public class Strand{
	
	public static <E extends Comparable<? super E>> 
	LinkedList<E> strandSort(LinkedList<E> list){
		if(list.size() <= 1) return list;

		LinkedList<E> result = new LinkedList<E>();
		while(list.size() > 0){
			LinkedList<E> sorted = new LinkedList<E>();
			sorted.add(list.removeFirst()); 
			for(Iterator<E> it = list.iterator(); it.hasNext(); ){
				E elem = it.next();
				if(sorted.peekLast().compareTo(elem) <= 0){
					sorted.addLast(elem); 
					it.remove();
				}
			}
			result = merge(sorted, result);
		}
		return result;
	}

	private static <E extends Comparable<? super E>>
	LinkedList<E> merge(LinkedList<E> left, LinkedList<E> right){
		LinkedList<E> result = new LinkedList<E>();
		while(!left.isEmpty() && !right.isEmpty()){
			
			if(left.peek().compareTo(right.peek()) <= 0)
				result.add(left.remove());
			else
				result.add(right.remove());
		}
		result.addAll(left);
		result.addAll(right);
		return result;
	}
	
	public static void main(String[] args){
		System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,1,2,4,5))));
		System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,5))));
		System.out.println(strandSort(new LinkedList<Integer>(Arrays.asList(3,3,1,2,4,3,5,6))));
	}
}



Python: def merge_list(a, b):
	out = []
	while len(a) and len(b):
		if a[0] < b[0]:
			out.append(a.pop(0))
		else:
			out.append(b.pop(0))
	out += a
	out += b
	return out

def strand(a):
	i, s = 0, [a.pop(0)]
	while i < len(a):
		if a[i] > s[-1]:
			s.append(a.pop(i))
		else:
			i += 1
	return s

def strand_sort(a):
	out = strand(a)
	while len(a):
		out = merge_list(out, strand(a))
	return out

print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
Task: Additive primes





Java: public class additivePrimes {

    public static void main(String[] args) {
        int additive_primes = 0;
        for (int i = 2; i < 500; i++) {
            if(isPrime(i) && isPrime(digitSum(i))){
                additive_primes++;
                System.out.print(i + " ");
            }
        }
        System.out.print("\nFound " + additive_primes + " additive primes less than 500");
    }

    static boolean isPrime(int n) {
        int counter = 1;
        if (n < 2 || (n != 2 && n % 2 == 0) || (n != 3 && n % 3 == 0)) {
            return false;
        }
        while (counter * 6 - 1 <= Math.sqrt(n)) {
            if (n % (counter * 6 - 1) == 0 || n % (counter * 6 + 1) == 0) {
                return false;
            } else {
                counter++;
            }
        }
        return true;
    }

    static int digitSum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += n % 10;
            n /= 10;
        }
        return sum;
    }
}



Python: def is_prime(n: int) -> bool:
    if n <= 3:
        return n > 1
    if n % 2 == 0 or n % 3 == 0:
        return False
    i = 5
    while i ** 2 <= n:
        if n % i == 0 or n % (i + 2) == 0:
            return False
        i += 6
    return True

def digit_sum(n: int) -> int:
    sum = 0
    while n > 0:
        sum += n % 10
        n //= 10
    return sum

def main() -> None:
    additive_primes = 0
    for i in range(2, 500):
        if is_prime(i) and is_prime(digit_sum(i)):
            additive_primes += 1
            print(i, end=" ")
    print(f"\nFound {additive_primes} additive primes less than 500")

if __name__ == "__main__":
    main()
Task: Perfect totient numbers





Java: import java.util.ArrayList;
import java.util.List;

public class PerfectTotientNumbers {

    public static void main(String[] args) {
        computePhi();
        int n = 20;
        System.out.printf("The first %d perfect totient numbers:%n%s%n", n, perfectTotient(n));
    }
    
    private static final List<Integer> perfectTotient(int n) {
        int test = 2;
        List<Integer> results = new ArrayList<Integer>();
        for ( int i = 0 ; i < n ; test++ ) {
            int phiLoop = test;
            int sum = 0;
            do {
                phiLoop = phi[phiLoop];
                sum += phiLoop;
            } while ( phiLoop > 1);
            if ( sum == test ) {
                i++;
                results.add(test);
            }
        }
        return results;
    }

    private static final int max = 100000;
    private static final int[] phi = new int[max+1];

    private static final void computePhi() {
        for ( int i = 1 ; i <= max ; i++ ) {
            phi[i] = i;
        }
        for ( int i = 2 ; i <= max ; i++ ) {
            if (phi[i] < i) continue;
            for ( int j = i ; j <= max ; j += i ) {
                phi[j] -= phi[j] / i;
            }
        }
    }

}



Python: from math import gcd
from functools import lru_cache
from itertools import islice, count

@lru_cache(maxsize=None)
def  φ(n):
    return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)

def perfect_totient():
    for n0 in count(1):
        parts, n = 0, n0
        while n != 1:
            n = φ(n)
            parts += n
        if parts == n0:
            yield n0
        

if __name__ == '__main__':
    print(list(islice(perfect_totient(), 20)))
Task: Delegates





Java: interface Thingable {
    String thing();
}

class Delegator {
    public Thingable delegate;

    public String operation() {
        if (delegate == null)
            return "default implementation";
        else
            return delegate.thing();
    }
}

class Delegate implements Thingable {
    public String thing() {
        return "delegate implementation";
    }
}



public class DelegateExample {
    public static void main(String[] args) {
        
        Delegator a = new Delegator();
        assert a.operation().equals("default implementation");

        
        Delegate d = new Delegate();
        a.delegate = d;
        assert a.operation().equals("delegate implementation");

        
        a.delegate = new Thingable() {
                public String thing() {
                    return "anonymous delegate implementation";
                }
            };
        assert a.operation().equals("anonymous delegate implementation");
    }
}



Python: class Delegator:
   def __init__(self):
      self.delegate = None
   def operation(self):
       if hasattr(self.delegate, 'thing') and callable(self.delegate.thing):
          return self.delegate.thing()
       return 'default implementation'

class Delegate:
   def thing(self):
      return 'delegate implementation'

if __name__ == '__main__':

   
   a = Delegator()
   assert a.operation() == 'default implementation'

   
   a.delegate = 'A delegate may be any object'
   assert a.operation() == 'default implementation'

   
   a.delegate = Delegate()
   assert a.operation() == 'delegate implementation'
Task: Sum of divisors





Java: public class DivisorSum {
    private static long divisorSum(long n) {
        var total = 1L;
        var power = 2L;
        
        for (; (n & 1) == 0; power <<= 1, n >>= 1) {
            total += power;
        }
        
        for (long p = 3; p * p <= n; p += 2) {
            long sum = 1;
            for (power = p; n % p == 0; power *= p, n /= p) {
                sum += power;
            }
            total *= sum;
        }
        
        if (n > 1) {
            total *= n + 1;
        }
        return total;
    }

    public static void main(String[] args) {
        final long limit = 100;
        System.out.printf("Sum of divisors for the first %d positive integers:%n", limit);
        for (long n = 1; n <= limit; ++n) {
            System.out.printf("%4d", divisorSum(n));
            if (n % 10 == 0) {
                System.out.println();
            }
        }
    }
}



Python: def factorize(n):
    assert(isinstance(n, int))
    if n < 0: 
        n = -n 
    if n < 2: 
        return 
    k = 0 
    while 0 == n%2: 
        k += 1 
        n //= 2 
    if 0 < k: 
        yield (2,k) 
    p = 3 
    while p*p <= n: 
        k = 0 
        while 0 == n%p: 
            k += 1 
            n //= p 
        if 0 < k: 
            yield (p,k)
        p += 2 
    if 1 < n: 
        yield (n,1) 

def sum_of_divisors(n): 
    assert(n != 0) 
    ans = 1 
    for (p,k) in factorize(n): 
        ans *= (pow(p,k+1) - 1)//(p-1) 
    return ans 
    
if __name__ == "__main__":
    print([sum_of_divisors(n) for n in range(1,101)])
Task: Enforced immutability





Java: final int immutableInt = 4;
int mutableInt = 4;
mutableInt = 6; 
immutableInt = 6; 



Python: >>> s = "Hello"
>>> s[0] = "h"

Traceback (most recent call last):
  File "<pyshell
    s[0] = "h"
TypeError: 'str' object does not support item assignment
Task: Spiral matrix





Java: public class Blah {

  public static void main(String[] args) {
    print2dArray(getSpiralArray(5));
  }

  public static int[][] getSpiralArray(int dimension) {
    int[][] spiralArray = new int[dimension][dimension];

    int numConcentricSquares = (int) Math.ceil((dimension) / 2.0);

    int j;
    int sideLen = dimension;
    int currNum = 0;

    for (int i = 0; i < numConcentricSquares; i++) {
      
      for (j = 0; j < sideLen; j++) {
        spiralArray[i][i + j] = currNum++;
      }

      
      for (j = 1; j < sideLen; j++) {
        spiralArray[i + j][dimension - 1 - i] = currNum++;
      }

      
      for (j = sideLen - 2; j > -1; j--) {
        spiralArray[dimension - 1 - i][i + j] = currNum++;
      }

      
      for (j = sideLen - 2; j > 0; j--) {
        spiralArray[i + j][i] = currNum++;
      }

      sideLen -= 2;
    }

    return spiralArray;
  }

  public static void print2dArray(int[][] array) {
    for (int[] row : array) {
      for (int elem : row) {
        System.out.printf("%3d", elem);
      }
      System.out.println();
    }
  }
}



Python: def spiral(n):
    dx,dy = 1,0            
    x,y = 0,0              
    myarray = [[None]* n for j in range(n)]
    for i in xrange(n**2):
        myarray[x][y] = i
        nx,ny = x+dx, y+dy
        if 0<=nx<n and 0<=ny<n and myarray[nx][ny] == None:
            x,y = nx,ny
        else:
            dx,dy = -dy,dx
            x,y = x+dx, y+dy
    return myarray

def printspiral(myarray):
    n = range(len(myarray))
    for y in n:
        for x in n:
            print "%2i" % myarray[x][y],
        print

printspiral(spiral(5))