Front-end programming problem: a positive integer n can be expressed as the sum of a continuous sequence of positive numbers, finding the longest expression, for example, 15 = 1, 2, 3, 4, 5.

The

positive integer n can be expressed as the sum of consecutive sequences of positive numbers, finding the longest expression, for example, 15 = 1, 2, 3, 4, 5. Ask the boss for an answer!

Jul.06,2022

function getNum(n, count) {
        if (typeof n !== "number" && n % 1 !== 0 && n >= 3) return;
        //
        var disc = Math.pow(count, 2) - 4 * 1 * -2 * n,
            x1,
            x2,
            result;
        if (disc < 0) {
            return;
        } else {
            x1 = (-1 + Math.sqrt(disc)) / 2;
            x2 = (-1 - Math.sqrt(disc)) / 2;
            if (x1 > 0 && x1 % 1 === 0) {
                result = forNum(x1, n, count);
            } else if (x2 > 0 && x2 % 1 === 0) {
                result = forNum(x2, n, count);
            } else {
                result = "!";
            }
        }
        return result;
    }
    function forNum(x, n, count) {
        var total = 0,
            arr = [];
        for (var i = count; i <= x; iPP) {
            total += i;
            if (total > n) {
                break;
            } else {
                arr.push(i);
            }
        }
        if (arr.length > 1) {
            var expressionStr = '';
            arr.map(function(item,index){
                expressionStr += item.toString() + '+';
            })
            return expressionStr.slice(0,expressionStr.length - 1);
        } else {
            return "!";
        }
    }

the first parameter is a positive integer n , and the second parameter is the first value of the longest positive sequence. The algorithm is based on the arithmetic sequence. Here you need to know the equidifference sequence, because the tolerance is d = 1 , and when the first value is count , the summation formula sn = n * count + (n-1) * n / 2 * 1 = (n ^ 2 + n) / 2 is the longest sequence. If this condition is satisfied, each term of the longest sequence can be obtained, and then added to an array and traversed through each item in the array. And then return an expression.


  

is that all right? 2 = 1 +?

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3a9c8-2af6e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3a9c8-2af6e.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?