题目:给定一个正整数 N,试求有多少组连续正整数满足所有数字之和为 N?
示例 1:
输入: 5
输出: 2
解释: 5 = 5 = 2 + 3,共有两组连续整数([5],[2,3])求和后为 5。
示例 2:
输入: 9
输出: 3
解释: 9 = 9 = 4 + 5 = 2 + 3 + 4
示例 3:
输入: 15
输出: 4
解释: 15 = 15 = 8 + 7 = 4 + 5 + 6 = 1 + 2 + 3 + 4 + 5
说明: 1 <= N <= 10 ^ 9
/*
N = (p+0)+(p+1)+(p+2)+...+(p+i-1)
= p*i +i*(i-1)/2
===>
2*N = (p*2+i-1)*i (p,i都是正整数)
*/
import "math"
func consecutiveNumbersSum(N int) int {
var sum = 0
dataChan := make(chan int, 10)
outChan := make(chan byte, 10)
go func() {
defer close(dataChan)
for i := 1; float64(i) <= math.Sqrt(float64(2*N)); i++ {
if (2*N)%i == 0 {
dataChan <- i
}
}
}()
go func() {
for {
if i, ok := <-dataChan; !ok {
close(outChan)
return
} else {
p := (2*N)/i - i - 1
if p >= 0 && (p&1 == 0) {
// fmt.Println("offset,i", p/2, i)
outChan <- 0
}
}
}
}()
for {
if _, ok := <-outChan; ok {
sum++
} else {
break
}
}
return sum
}