我正在编写一个编码问题,作为它的子部分,我遇到了这个问题:
我们给出一个数字x,我们将它平方,因此数字变为x ^ 2.现在我们有从1到x ^ 2的数字,例如:如果number = 4; 那么4 ^ 2 = 16
1 ----->1
2 3 ----->2
4 5 6 ----->3
7 8 9 10 ----->4
11 12 13 ----->5
14 15 ----->6
16 ----->7
Run Code Online (Sandbox Code Playgroud)
现在我给了一个数字说k,我需要告诉它属于哪个组.这里8属于第4组.
我的想法是从1开始并将计数初始化为1并检查1 <8?如果是,则添加2比1(上一个总和),将计数增加到2并检查3 <8?如果是,则添加3到3(上一个总和),将计数增加到3并检查是否6 <8如果是,则添加4到6,将计数增加到4并检查10 <9?如果没有那么退出.所以组号.算是4.
但是有没有比我的方法快的方法?
编辑1: 我忘了在我的算法中提到当计数达到给定数字时,在前面的示例中为4,那么我不应该添加5但是3.例如:
如果要搜索的数字是14那么
1<14 yes then add 2
3<14 yes then add 3
6<14 yes then add 4
10<14 yes then add **3** ---->here I need to add 3 instead of 5
13<14 yes then add **2** ---->here I need to add 2 instead of 6
15<14 No so output count.
Run Code Online (Sandbox Code Playgroud)
可以使用if条件添加3而不是5但是有任何方法可以根据x的值自动增加然后减少值(参见上面的示例以了解x指的是什么)
矩形的上半部分是三角形:
1 ----->1
2 3 ----->2
4 5 6 ----->3
7 8 9 10 ----->4
Run Code Online (Sandbox Code Playgroud)
并且右侧(1,3,6,10)的数字称为三角形数字.那里的反公式(在副标题"三角形根和三角数测试"下)可以用于你的问题:
def group(x, number):
if number <= x^2 / 2 :
return ceiling( (sqrt(8*number+1) - 1) / 2 )
else:
return 2*x - group(x, x^2+1-number)
Run Code Online (Sandbox Code Playgroud)