WeixiangYan/CodeTransOcean huggingface dataset:
Task: Left factorials





Java: import java.math.BigInteger;

public class LeftFac{
	public static BigInteger factorial(BigInteger n){
		BigInteger ans = BigInteger.ONE;
		for(BigInteger x = BigInteger.ONE; x.compareTo(n) <= 0; x = x.add(BigInteger.ONE)){
			ans = ans.multiply(x);
		}
		return ans;
	}
	
	public static BigInteger leftFact(BigInteger n){
		BigInteger ans = BigInteger.ZERO;
		for(BigInteger k = BigInteger.ZERO; k.compareTo(n.subtract(BigInteger.ONE)) <= 0; k = k.add(BigInteger.ONE)){
			ans = ans.add(factorial(k));
		}
		return ans;
	}
	
	public static void main(String[] args){
		for(int i = 0; i <= 10; i++){
			System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
		}
		
		for(int i = 20; i <= 110; i += 10){
			System.out.println("!" + i + " = " + leftFact(BigInteger.valueOf(i)));
		}
		
		for(int i = 1000; i <= 10000; i += 1000){
			System.out.println("!" + i + " has " + leftFact(BigInteger.valueOf(i)).toString().length() + " digits");
		}
	}
}
Task: Strange unique prime triplets





Java: import java.util.*;

public class StrangeUniquePrimeTriplets {
    public static void main(String[] args) {
        strangeUniquePrimeTriplets(30, true);
        strangeUniquePrimeTriplets(1000, false);
    }

    private static void strangeUniquePrimeTriplets(int limit, boolean verbose) {
        boolean[] sieve = primeSieve(limit * 3);
        List<Integer> primeList = new ArrayList<>();
        for (int p = 3; p < limit; p += 2) {
            if (sieve[p])
                primeList.add(p);
        }
        int n = primeList.size();
        
        int[] primes = new int[n];
        for (int i = 0; i < n; ++i)
            primes[i] = primeList.get(i);
        int count = 0;
        if (verbose)
            System.out.printf("Strange unique prime triplets < %d:\n", limit);
        for (int i = 0; i + 2 < n; ++i) {
            for (int j = i + 1; j + 1 < n; ++j) {
                int s = primes[i] + primes[j];
                for (int k = j + 1; k < n; ++k) {
                    int sum = s + primes[k];
                    if (sieve[sum]) {
                        ++count;
                        if (verbose)
                            System.out.printf("%2d + %2d + %2d = %2d\n", primes[i], primes[j], primes[k], sum);
                    }
                }
            }
        }
        System.out.printf("\nCount of strange unique prime triplets < %d is %d.\n", limit, count);
    }

    private static boolean[] primeSieve(int limit) {
        boolean[] sieve = new boolean[limit];
        Arrays.fill(sieve, true);
        if (limit > 0)
            sieve[0] = false;
        if (limit > 1)
            sieve[1] = false;
        for (int i = 4; i < limit; i += 2)
            sieve[i] = false;
        for (int p = 3; ; p += 2) {
            int q = p * p;
            if (q >= limit)
                break;
            if (sieve[p]) {
                int inc = 2 * p;
                for (; q < limit; q += inc)
                    sieve[q] = false;
            }
        }
        return sieve;
    }
}
Task: Strange plus numbers





Java: public class Strange {
    private static final boolean[] p = {
        false, false, true,  true,  false,
        true,  false, true,  false, false,
        false, true,  false, true,  false,
        false, false, true,  false
    };

    public static boolean isstrange(long n) {
        if (n < 10) return false;
        for (; n >= 10; n /= 10) {
            if (!p[(int)(n%10 + (n/10)%10)]) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        long nMin = Long.parseLong(args[0]);
        long nMax = Long.parseLong(args[1]);
        int k = 0;
     
        for (long n = nMin; n <= nMax; n++) {
            if (isstrange(n)) {
                System.out.print(n + (++k%10 != 0 ? " " : "\n"));
            }
        }
    }
}
Task: Smarandache prime-digital sequence





Java: public class SmarandachePrimeDigitalSequence {

    public static void main(String[] args) {
        long s = getNextSmarandache(7);
        System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
        for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
            if ( isPrime(s) ) {
                System.out.printf("%d ", s);
                count++;
            }
        }
        System.out.printf("%n%n");
        for (int i = 2 ; i <=5 ; i++ ) {
            long n = (long) Math.pow(10, i);
            System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n));
        }
    }
    
    private static final long getSmarandachePrime(long n) {
        if ( n < 10 ) {
            switch ((int) n) {
            case 1:  return 2;
            case 2:  return 3;
            case 3:  return 5;
            case 4:  return 7;
            }
        }
        long s = getNextSmarandache(7);
        long result = 0;
        for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {
            if ( isPrime(s) ) {
                count++;
                result = s;
            }
        }
        return result;
    }
    
    private static final boolean isPrime(long test) {
        if ( test % 2 == 0 ) return false;
        for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
            if ( test % i == 0 ) {
                return false;
            }
        }
        return true;
    }

    private static long getNextSmarandache(long n) {
        
        if ( n % 10 == 3 ) {
            return n+4;
        }
        long retVal = n-4;
        
        
        int k = 0;
        while ( n % 10 == 7 ) {
            k++;
            n /= 10;
        }
        
        
        long digit = n % 10;

        
        long coeff = (digit == 2 ? 1 : 2);
        
        
        retVal += coeff * Math.pow(10, k);
        
        
        while ( k > 1 ) {
            retVal -= 5 * Math.pow(10, k-1);
            k--;
        }
        
        
        return retVal;
    }

}
Task: Magic squares of doubly even order





Java: public class MagicSquareDoublyEven {

    public static void main(String[] args) {
        int n = 8;
        for (int[] row : magicSquareDoublyEven(n)) {
            for (int x : row)
                System.out.printf("%2s ", x);
            System.out.println();
        }
        System.out.printf("\nMagic constant: %d ", (n * n + 1) * n / 2);
    }

    static int[][] magicSquareDoublyEven(final int n) {
        if (n < 4 || n % 4 != 0)
            throw new IllegalArgumentException("base must be a positive "
                    + "multiple of 4");

        
        int bits = 0b1001_0110_0110_1001;
        int size = n * n;
        int mult = n / 4;  

        int[][] result = new int[n][n];

        for (int r = 0, i = 0; r < n; r++) {
            for (int c = 0; c < n; c++, i++) {
                int bitPos = c / mult + (r / mult) * 4;
                result[r][c] = (bits & (1 << bitPos)) != 0 ? i + 1 : size - i;
            }
        }
        return result;
    }
}
Task: Plasma effect





Java: import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import static java.awt.image.BufferedImage.*;
import static java.lang.Math.*;
import javax.swing.*;

public class PlasmaEffect extends JPanel {
    float[][] plasma;
    float hueShift = 0;
    BufferedImage img;

    public PlasmaEffect() {
        Dimension dim = new Dimension(640, 640);
        setPreferredSize(dim);
        setBackground(Color.white);

        img = new BufferedImage(dim.width, dim.height, TYPE_INT_RGB);
        plasma = createPlasma(dim.height, dim.width);

        
        new Timer(42, (ActionEvent e) -> {
            hueShift = (hueShift + 0.02f) % 1;
            repaint();
        }).start();
    }

    float[][] createPlasma(int w, int h) {
        float[][] buffer = new float[h][w];

        for (int y = 0; y < h; y++)
            for (int x = 0; x < w; x++) {

                double value = sin(x / 16.0);
                value += sin(y / 8.0);
                value += sin((x + y) / 16.0);
                value += sin(sqrt(x * x + y * y) / 8.0);
                value += 4; 
                value /= 8; 

                
                assert (value >= 0.0 && value <= 1.0) : "Hue value out of bounds";

                buffer[y][x] = (float) value;
            }
        return buffer;
    }

    void drawPlasma(Graphics2D g) {
        int h = plasma.length;
        int w = plasma[0].length;
        for (int y = 0; y < h; y++)
            for (int x = 0; x < w; x++) {
                float hue = hueShift + plasma[y][x] % 1;
                img.setRGB(x, y, Color.HSBtoRGB(hue, 1, 1));
            }
        g.drawImage(img, 0, 0, null);
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        drawPlasma(g);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Plasma Effect");
            f.setResizable(false);
            f.add(new PlasmaEffect(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}
Task: Square-free integers





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

public class SquareFree
{
    private static List<Long> sieve(long limit) {
        List<Long> primes = new ArrayList<Long>();
        primes.add(2L);
        boolean[] c = new boolean[(int)limit + 1]; 
        
        long p = 3;
        for (;;) {
            long p2 = p * p;
            if (p2 > limit) break;
            for (long i = p2; i <= limit; i += 2 * p) c[(int)i] = true;
            for (;;) {
                p += 2;
                if (!c[(int)p]) break;
            }
        }
        for (long i = 3; i <= limit; i += 2) {
            if (!c[(int)i]) primes.add(i);
        }
        return primes;
    }

    private static List<Long> squareFree(long from, long to) {
        long limit = (long)Math.sqrt((double)to);
        List<Long> primes = sieve(limit);
        List<Long> results = new ArrayList<Long>();

        outer: for (long i = from; i <= to; i++) {
            for (long p : primes) {
                long p2 = p * p;
                if (p2 > i) break;
                if (i % p2 == 0) continue outer;
            }
            results.add(i);
        }
        return results;
    }

    private final static long TRILLION = 1000000000000L;

    public static void main(String[] args) {
        System.out.println("Square-free integers from 1 to 145:");
        List<Long> sf = squareFree(1, 145);
        for (int i = 0; i < sf.size(); i++) {
            if (i > 0 && i % 20 == 0) {
                System.out.println();
            }
            System.out.printf("%4d", sf.get(i));
        }

        System.out.print("\n\nSquare-free integers");
        System.out.printf(" from %d to %d:\n", TRILLION, TRILLION + 145);
        sf = squareFree(TRILLION, TRILLION + 145);
        for (int i = 0; i < sf.size(); i++) {
            if (i > 0 && i % 5 == 0) System.out.println();
            System.out.printf("%14d", sf.get(i));
        }

        System.out.println("\n\nNumber of square-free integers:\n");
        long[] tos = {100, 1000, 10000, 100000, 1000000};
        for (long to : tos) {
            System.out.printf("  from %d to %d = %d\n", 1, to, squareFree(1, to).size());
        }
    }
}
Task: Self numbers





Java: public class SelfNumbers {
    private static final int MC = 103 * 1000 * 10000 + 11 * 9 + 1;
    private static final boolean[] SV = new boolean[MC + 1];

    private static void sieve() {
        int[] dS = new int[10_000];
        for (int a = 9, i = 9999; a >= 0; a--) {
            for (int b = 9; b >= 0; b--) {
                for (int c = 9, s = a + b; c >= 0; c--) {
                    for (int d = 9, t = s + c; d >= 0; d--) {
                        dS[i--] = t + d;
                    }
                }
            }
        }
        for (int a = 0, n = 0; a < 103; a++) {
            for (int b = 0, d = dS[a]; b < 1000; b++, n += 10000) {
                for (int c = 0, s = d + dS[b] + n; c < 10000; c++) {
                    SV[dS[c] + s++] = true;
                }
            }
        }
    }

    public static void main(String[] args) {
        sieve();
        System.out.println("The first 50 self numbers are:");
        for (int i = 0, count = 0; count <= 50; i++) {
            if (!SV[i]) {
                count++;
                if (count <= 50) {
                    System.out.printf("%d ", i);
                } else {
                    System.out.printf("%n%n       Index     Self number%n");
                }
            }
        }
        for (int i = 0, limit = 1, count = 0; i < MC; i++) {
            if (!SV[i]) {
                if (++count == limit) {
                    System.out.printf("%,12d   %,13d%n", count, i);
                    limit *= 10;
                }
            }
        }
    }
}
Task: Increasing gaps between consecutive Niven numbers





Java: public class NivenNumberGaps {

    
    
    public static void main(String[] args) {
        long prevGap = 0;
        long prevN = 1;
        long index = 0;
        System.out.println("Gap      Gap Index   Starting Niven");
        for ( long n = 2 ; n < 20_000_000_000l ; n++ ) {
            if ( isNiven(n) ) {
                index++;
                long curGap = n - prevN;
                if ( curGap > prevGap ) {
                    System.out.printf("%3d  %,13d  %,15d%n", curGap, index, prevN);
                    prevGap = curGap;
                }
                prevN = n;
            }
        }
    }
    
    public static boolean isNiven(long n) {
        long sum = 0;
        long nSave = n;
        while ( n > 0 ) {
            sum += n % 10;
            n /= 10;
        }
        return nSave % sum == 0;
    }

}
Task: Old Russian measure of length





Java: public class OldRussianMeasures {

    final static String[] keys = {"tochka", "liniya", "centimeter", "diuym",
        "vershok", "piad", "fut", "arshin", "meter", "sazhen", "kilometer",
        "versta", "milia"};

    final static double[] values = {0.000254, 0.00254, 0.01,0.0254,
        0.04445, 0.1778, 0.3048, 0.7112, 1.0, 2.1336, 1000.0,
        1066.8, 7467.6};

    public static void main(String[] a) {
        if (a.length == 2 && a[0].matches("[+-]?\\d*(\\.\\d+)?")) {
            double inputVal = lookup(a[1]);
            if (!Double.isNaN(inputVal)) {
                double magnitude = Double.parseDouble(a[0]);
                double meters = magnitude * inputVal;
                System.out.printf("%s %s to: %n%n", a[0], a[1]);
                for (String k: keys)
                    System.out.printf("%10s: %g%n", k, meters / lookup(k));
                return;
            }
        }
        System.out.println("Please provide a number and unit");

    }

    public static double lookup(String key) {
        for (int i = 0; i < keys.length; i++)
            if (keys[i].equals(key))
                return values[i];
        return Double.NaN;
    }
}
Task: Pancake numbers





Java: public class Pancake {
    private static int pancake(int n) {
        int gap = 2;
        int sum = 2;
        int adj = -1;
        while (sum < n) {
            adj++;
            gap = 2 * gap - 1;
            sum += gap;
        }
        return n + adj;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 4; i++) {
            for (int j = 1; j < 6; j++) {
                int n = 5 * i + j;
                System.out.printf("p(%2d) = %2d  ", n, pancake(n));
            }
            System.out.println();
        }
    }
}
Task: Test integerness





Java: import java.math.BigDecimal;
import java.util.List;

public class TestIntegerness {
    private static boolean isLong(double d) {
        return isLong(d, 0.0);
    }

    private static boolean isLong(double d, double tolerance) {
        return (d - Math.floor(d)) <= tolerance || (Math.ceil(d) - d) <= tolerance;
    }

    @SuppressWarnings("ResultOfMethodCallIgnored")
    private static boolean isBigInteger(BigDecimal bd) {
        try {
            bd.toBigIntegerExact();
            return true;
        } catch (ArithmeticException ex) {
            return false;
        }
    }

    private static class Rational {
        long num;
        long denom;

        Rational(int num, int denom) {
            this.num = num;
            this.denom = denom;
        }

        boolean isLong() {
            return num % denom == 0;
        }

        @Override
        public String toString() {
            return String.format("%s/%s", num, denom);
        }
    }

    private static class Complex {
        double real;
        double imag;

        Complex(double real, double imag) {
            this.real = real;
            this.imag = imag;
        }

        boolean isLong() {
            return TestIntegerness.isLong(real) && imag == 0.0;
        }

        @Override
        public String toString() {
            if (imag >= 0.0) {
                return String.format("%s + %si", real, imag);
            }
            return String.format("%s - %si", real, imag);
        }
    }

    public static void main(String[] args) {
        List<Double> da = List.of(25.000000, 24.999999, 25.000100);
        for (Double d : da) {
            boolean exact = isLong(d);
            System.out.printf("%.6f is %s integer%n", d, exact ? "an" : "not an");
        }
        System.out.println();

        double tolerance = 0.00001;
        System.out.printf("With a tolerance of %.5f:%n", tolerance);
        for (Double d : da) {
            boolean fuzzy = isLong(d, tolerance);
            System.out.printf("%.6f is %s integer%n", d, fuzzy ? "an" : "not an");
        }
        System.out.println();

        List<Double> fa = List.of(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY);
        for (Double f : fa) {
            boolean exact = !f.isNaN() && !f.isInfinite() && isBigInteger(new BigDecimal(f.toString()));
            System.out.printf("%s is %s integer%n", f, exact ? "an" : "not an");
        }
        System.out.println();

        List<Complex> ca = List.of(new Complex(5.0, 0.0), new Complex(5.0, -5.0));
        for (Complex c : ca) {
            boolean exact = c.isLong();
            System.out.printf("%s is %s integer%n", c, exact ? "an" : "not an");
        }
        System.out.println();

        List<Rational> ra = List.of(new Rational(24, 8), new Rational(-5, 1), new Rational(17, 2));
        for (Rational r : ra) {
            boolean exact = r.isLong();
            System.out.printf("%s is %s integer%n", r, exact ? "an" : "not an");
        }
    }
}
Task: Linux CPU utilization





Java: import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.NumberFormat;
import java.time.Duration;
import java.util.Timer;
import java.util.TimerTask;


public class Main {

    public static void main(String[] args) throws FileNotFoundException {
        
        final var period = Duration.ofSeconds(1);
        new Timer().schedule(new CpuUtilizationTask(), 0, period.toMillis());
    }

    
    static class CpuUtilizationTask extends TimerTask {

        private final String STAT_FILE_HEADER = "cpu  ";
        private final NumberFormat percentFormatter;
        private final RandomAccessFile statPointer;
        long previousIdleTime = 0, previousTotalTime = 0;

        public CpuUtilizationTask() throws FileNotFoundException {
            this.percentFormatter = NumberFormat.getPercentInstance();
            percentFormatter.setMaximumFractionDigits(2);
            var statFile = new File("/proc/stat");
            
            this.statPointer = new RandomAccessFile(statFile, "r");
        }

        @Override
        public void run() {

            try {
                var values = statPointer.readLine()
                        .substring(STAT_FILE_HEADER.length())
                        .split(" ");

                
                var idleTime = Long.parseUnsignedLong(values[3]);
                var totalTime = 0L;
                for (String value : values) {
                    totalTime += Long.parseUnsignedLong(value);
                }

                var idleTimeDelta = idleTime - previousIdleTime;
                var totalTimeDelta = totalTime - previousTotalTime;
                var utilization = 1 - ((double) idleTimeDelta) / totalTimeDelta;

                
                System.out.println(percentFormatter.format(utilization));

                previousIdleTime = idleTime;
                previousTotalTime = totalTime;

                
                statPointer.seek(0);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }
}
Task: Ulam numbers





Java: public class UlamNumbers {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int n = 1; n <= 100000; n *= 10) {
            System.out.printf("Ulam(%d) = %d\n", n, ulam(n));
        }
        long finish = System.currentTimeMillis();
        System.out.printf("Elapsed time: %.3f seconds\n", (finish - start)/1000.0);
    }

    private static int ulam(int n) {
        int[] ulams = new int[Math.max(n, 2)];
        ulams[0] = 1;
        ulams[1] = 2;
        int sieveLength = 2;
        int[] sieve = new int[sieveLength];
        sieve[0] = sieve[1] = 1;
        for (int u = 2, ulen = 2; ulen < n; ) {
            sieveLength = u + ulams[ulen - 2];
            sieve = extend(sieve, sieveLength);
            for (int i = 0; i < ulen - 1; ++i)
                ++sieve[u + ulams[i] - 1];
            for (int i = u; i < sieveLength; ++i) {
                if (sieve[i] == 1) {
                    u = i + 1;
                    ulams[ulen++] = u;
                    break;
                }
            }
        }
        return ulams[n - 1];
    }

    private static int[] extend(int[] array, int minLength) {
        if (minLength <= array.length)
            return array;
        int newLength = 2 * array.length;
        while (newLength < minLength)
            newLength *= 2;
        int[] newArray = new int[newLength];
        System.arraycopy(array, 0, newArray, 0, array.length);
        return newArray;
    }
}