C语言 在一系列数字中找到当前步长



我尝试用C语言创建一个简单的函数,该函数允许我们通过给出当前行号,总行数和步数来找到一系列数字的当前步数…

数列示例:

line 0  - 0   --
line 1  - 0     |--> STEP 1
line 2  - 0   --
line 3  - 1   --
line 4  - 1     |--> STEP 2
line 5  - 1     |
line 6  - 1   --
line 7  - 2   --
line 8  - 2     |
line 9  - 2     |--> STEP 3
line 10 - 2     |
line 11 - 2   --
Parameters : currentLine = 5; totalLines = 12; steps = 3;

在这种情况下,我有三个不同的步骤,所有步骤都增加了一行。在行号旁边,每一步都用相同的数字表示。

在我的示例中,我选择currentLine = 5,它表示我们想要找到当前步骤的行。所以在我的例子中,我需要找到:2.

给出当前行当前步的函数原型:

int findCurrentStep(int currentLine, int totalLines, int steps);

我只是想知道如何计算它?

编辑:谢谢你的回答,我只是做了另一个方法。
int findCurrentStep(int currentLine, int totalLines, int steps)
{
    int step;
    int trim_lines;
    step = steps;
    trim_lines = totalLines;
    while (currentLine <= trim_lines -1)
    {
        trim_lines = totalLines - 3 + steps - 1;
        step--;
    }
    return step;
}

EDIT: -

这是一个一步解决方案。

您需要找到currentLine等于或小于以3开头的AP的前r项。第一个总和超过currentLine的项就是currentStep。

假设currentLine小于等于AP的第一个r项的和。

所以,currentLine <= 3 +…* 1.

伪代码:

initialStep = 3;  // initialStep is 3 in this case.
sum = currentLine;  .
currentStep = 0;
while(sum > initialStep){
   sum -= initialStep;
   initialStep = intialStep + 1;
   currentStep++;
}
requiredAnswer = currentStep + 1;

你的答案应该是(currentStep + 1)在循环之后,因为当条件失败时循环将被终止。

如果有x步和n总行,则第1步出现的次数为a
然后,如问题所示,

a + (a+1) + (a+2) + ... + (a+x-1) = n  //since x steps and n total lines

因此,这意味着

x * (2*a + x - 1) = 2*n

现在,因为我们知道xn,解出a
一旦你知道a,如果你的"to find"当前行是c,你可以看到k,这个不等式是满足的:

a + (a+1) + ... (a+k) < c <= a + (a+1) + ...(a+k+1)

那么,k+1就是你的答案。

相关内容

最新更新