描述
A friend of mine takes a sequence of numbers from 1 to n (where n > 0).
Within that sequence, he chooses two numbers, a and b.
He says that the product of a and b should be equal to the sum of all numbers in the sequence, excluding a and b.
Given a number n, could you tell me the numbers he excluded from the sequence?
The function takes the parameter: n (n is always strictly greater than 0) and returns an array or a string (depending on the language) of the form:
[(a, b), …] or [[a, b], …] or {{a, b}, …} or or [{a, b}, …]
with all (a, b) which are the possible removed numbers in the sequence 1 to n.
[(a, b), …] or [[a, b], …] or {{a, b}, …} or …will be sorted in increasing order of the “a”.
It happens that there are several possible (a, b). The function returns an empty array (or an empty string) if no possible numbers are found which will prove that my friend has not told the truth!
Examples:
removNb(26) should return { {15, 21}, {21, 15} }
分析
方法1:
从1开始的m个数的和:
(
1
+
m
)
×
m
2
\frac{(1+m) \times m}{2}
2(1+m)×m
第一个数的范围应该是从1到m-1,第二个数的范围应该是从第一个数加1到m。依次遍历第一个数与第二个数,如果第一个数与第二个数的乘积,等于和减去这两个数,则满足要求。
方法2:
方法1利用内外两层循环,其时间复杂度为
O
(
n
2
)
\Omicron(n^2)
O(n2),当m很大时,运行时间过长。尝试逆向思维考虑:已知第一个数i与总和s,第二个数j需满足条件:
s
−
i
−
j
=
i
×
j
s-i-j=i \times j
s−i−j=i×j,即:
j
=
s
−
i
i
+
1
j=\frac{s-i}{i+1}
j=i+1s−i。此时只需遍历一次,判断
s
−
i
i
+
1
∈
(
1
,
m
]
\frac{s-i}{i+1} \in \lparen 1, m\rbrack
i+1s−i∈(1,m]即可。方法2的时间复杂度为
O
(
n
)
\Omicron(n)
O(n)。
实现
方法1:
func RemovNb(m uint64) (ret [][2]uint64) {
sum := (1 + m) * m / 2
for i := uint64(1); i < m; i++ {
for j := i + 1; j <= m; j++ {
if sum - i - j == i * j {
return [][2]uint64{[2]uint64{i, j}, [2]uint64{j, i}}
}
}
}
return
}
方法2:
func RemovNb(m uint64) (ret [][2]uint64) {
var i, sum uint64 = 0, (1 + m) * m / 2
for i = 1; i <= m; i++ {
if (sum - i) % (i + 1) == 0 {
j := (sum - i) / (i + 1)
if j <= m { ret = append(ret, [2]uint64{i, j}) }
}
}
return
}