skip to Main Content

EDIT:
The error happens when mod reaches a value greater than 2^32. Is there any way to increase how many bits mod has for memory, or a better war to store them?

I am running out of memory when running the code.

When running with iterations = 33, I get an error:

Mark-sweep 4622.7 (4655.5) -> 4212.1 (4244.9) MB, 2.0 / 0.0 ms (average mu = 0.993, current mu = 0.984) allocation failure; scavenge might not succeed

I am not entirely sure what this error means and couldn’t find much information online about it, can someone please help me? I am using VSC IDE if that helps.

function run(vals, count) {
let total = 0.5;
let { r, coef, cons, mod } = { ...vals };

        const startTime = performance.now();
    
        for (let j = 0; j < count; j++) {
            const newR = [];
            const newCoef = [];
            const newCons = [];
    
            for (let i = 0; i < r.length; i++) {
                const calculation = (coef[i] * r[i] + cons[i]) % mod;
    
                if (calculation === 0) {
                    if (coef[i] >= mod) {
                        newR.push(r[i], r[i] + mod);
                        newCoef.push(coef[i], coef[i]);
                        newCons.push(cons[i], cons[i]);
                    } else {
                        total += 1 / mod;
                    }
                } else {
                    newR.push(r[i], r[i] + mod);
                    newCoef.push(3 * coef[i], 3 * coef[i]);
                    newCons.push(3 * cons[i] + mod / 2, 3 * cons[i] + mod / 2);
                }
            }
    
            [r, coef, cons] = [newR, newCoef, newCons];
            mod *= 2;
        }
    
        const endTime = performance.now();
        const executionTime = endTime - startTime;
    
        return { total: total * 100, executionTime: executionTime.toFixed(2) };
    }    
    
    const initialVals = {
        r: [1],
        coef: [3],
        cons: [1],
        mod: 2,
    };
    
    const iterations = 32;
    
    const result = run(initialVals, iterations);
    console.log(`Iterations: ${iterations}, Total: ${result.total}%, Execution Time: ${result.executionTime}ms`);

2

Answers


  1. Chosen as BEST ANSWER

    Either use the JavaScript BigInt or use a different language like python.


  2. You could cache seen values and omit further calculations.

    function collatz(v, s = new Set) {
        if (s.has(v)) return [...s];
        s.add(v);
        return collatz(v % 2
            ? v * 3 + 1
            : v / 2
        , s);
    }
    
    console.log(collatz(33));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search