Topic:

/ / input an integer N output all and for continuous positive sequence / / column N, such as: 15 / input/output [[1, 2, 3, 4, 5], [4 and 6], [7, 8]]Copy the code
console.log(func(15)) 

function func(n) {
	let resultArr = [],
		tempArr = []
	if (n <= 2) return resultArr
	for (let i = 1; i <= (n - 1) / 2; i++) {
		for (let j = i + 1; j <= (n + 1) / 2; j++) {
			tempArr = createArr(i, j)
			if (sumArr(tempArr) === n) {
				resultArr.push(tempArr)
			} else if (sumArr(tempArr) > n) {
				break}}}return resultArr

	// create a continuous array from p to q
	function createArr(p, q) {
		let arr = []
		for (let i = p; i <= q; i++) {
			arr.push(i)
		}
		return arr
	}

	// find the sum of arrays
	function sumArr(arr) {
		return arr.reduce((sum, num) = > {
			returnsum + num; }}})Copy the code

Now let’s optimize the performance

Optimization: each time to create an array and array summation method, using arithmetic sequence summation, performance can be improved a lot

console.log(func(15))

function func(n) {
	let resultArr = []
	if (n <= 2) return resultArr
	for (let i = 1; i <= (n - 1) / 2; i++) {
		for (let j = i + 1; j <= (n + 1) / 2; j++) {
			// Summation of arithmetic sequences
			let sum = (j+1-i)*(i+j)/2
			if (sum === n) {
				resultArr.push(createArr(i, j))
			} else if (sum > n) {
				break}}}return resultArr

	// create a contiguous array from p to q
	function createArr(p, q) {
		let arr = []
		for (let i = p; i <= q; i++) {
			arr.push(i)
		}
		return arr
	}
}

Copy the code