Home > Blockchain >  Calculate number of possible operands
Calculate number of possible operands

Time:10-21

I need a function to calculate the number of possible addition equations for a given sum n.

The operands must always be in descending order, cannot be equal, and must be greater than 0.

So, 5 4 is valid but 4 5 5 5 3 3 3 or 9 0 are not. Only integers are used.

For instance:

n = 2. Result is 0

n = 3. Result is 1. 2 1

n = 5. Result is 2. 4 1 and 3 2

n = 10. Result is 8. 9 1, 8 2, 7 3, 6 4, 7 2 1, 6 3 1, 5 4 1, 5 3 2

CodePudding user response:

Just divide the number by 2 and floor the result:

function calc(num){
  return Math.floor(num/2);
} 

console.log(calc(5)) //4 1, 2 3
console.log(calc(6)) //1 5, 2 4, 3 3
console.log(calc(7)) //1 6, 2 5, 3 4
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

May I try it using php? It still need improved using recursive.

<?php
set_time_limit(3);

function get_little_number($n)
{
    echo "For n = $n";
    for($i = $n-1 ; $i > 0 ; $i --)
    {
        for($j = $i-1 ; $j > 0; $j--)
        {
            if($i   $j == $n)
            {
                echo "<br>$i   $j";
                continue;
            }
            for($k = $j-1 ; $k > 0; $k--)
            {
                if($i   $j   $k == $n)
                {
                    echo "<br>$i   $j   $k";
                    continue;
                }
                for($l = $k-1 ; $l > 0; $l--)
                {
                    if($i   $j   $k   $l == $n)
                    {
                        echo "<br>$i   $j   $k   l";
                        continue;
                    }
                    
                }
            }
        }
    }
}

echo get_little_number(2);
echo "<hr>";
echo get_little_number(3);
echo "<hr>";
echo get_little_number(5);
echo "<hr>";
echo get_little_number(7);
echo "<hr>";
echo get_little_number(10);
echo "<hr>";

Result:

Result

CodePudding user response:

Probably count with recursion, but the complexity is nearly exponential, counting for bigger numbers will be a problem

const next = ( fr, sum, expr ) => {
    // log a valid expression
    if (fr > 0) {
        // console.log(sum   '   '   expr);
    } else {
        expr = '';
    }
    
    let counts = 1;
    for (let trial = fr   1; trial * 2 < sum; trial  ) {
        counts  = next(trial, sum - trial, trial   (expr ? ('   '   expr) : ''));
    }
    return counts;
};

const count = ( n ) => {
    return next(0, n) - 1; // exclude n   0
};

for (let n = 1; n <= 10; n  ) {
    console.log(n   ' count '   count(n));
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related