在数组中添加数字序列并打印第n个数字

时间:2016-10-10 04:23:49

标签: java arrays sequence

我正在进行一项Java练习,它将打印序列号中的第n个数字。我刚刚在1,2,3,4,5,6,7,8,9,10等数组中完成了正常的序列号。所以如果n = 20,它会打印出20这个序列号。

现在,我想在数字序列中打印第n个数字,如下所示:

Start with a(0) = 0 
The next index is #1 (odd), so add 0 + 1 = 1 
The next index is #2 (even), so multiply 1 x 2 = 2 
The next index is #3 (odd), so add 2 + 3 = 5 
The next index is #4 (even), so multiply 5 x 4 = 20 
The next index is #5 (odd), so add 20 + 5 = 25 

基本上,如果索引是奇数,则添加到前一个术语。 如果索引是偶数,则乘以前一项

模式如下: 0,1,2,5,20,25,150,157,1256,1265,12650,12661,151932,151945,2127230,2127245,34035920,34035937,612646866等......

问题是,我不知道如何存储这些类型的序列号,以便我可以打印第n个数字。我被困住了直到:

    if ( number1 % 2 == 0)
{
    number1 = number1 * (1-number1);
}
else
{
    number1 = number1 + (1-number1);
}

提前致谢。

5 个答案:

答案 0 :(得分:2)

我认为你只是缺少一些用于存储上一次迭代状态的逻辑:

0, 1, 2, 5, 20, 25, 150, 157, 1256, 1265, 12650, 12661, 151932, 151945, ...

<强>输出:

>>> from nltk.corpus import PlaintextCorpusReader
>>> r = PlaintextCorpusReader('.','Dracula.txt')
>>> r.words()
['DRACULA', 'CHAPTER', 'I', 'JONATHAN', 'HARKER', "'", ...]
>>> r.sents()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/nltk/util.py", line 765, in __repr__
    for elt in self:
  File "/usr/local/lib/python3.5/dist-packages/nltk/corpus/reader/util.py", line 296, in iterate_from
    new_filepos = self._stream.tell()
  File "/usr/local/lib/python3.5/dist-packages/nltk/data.py", line 1333, in tell
    assert check1.startswith(check2) or check2.startswith(check1)
AssertionError

答案 1 :(得分:1)

假设number1是您的索引变量,请尝试以下代码段,

if ( number1 % 2 == 0){
        result= number1 * (result);
    }
    else
    {
        result= number1 + (result);
    }
    number1++;
    if(number1>=n){
     break;
    }

基本上,您需要进行迭代,直到达到n并继续将每次迭代的结果存储在名为result的单独变量中。

答案 2 :(得分:1)

只需将它们存储在数组中,使用索引获取第n个。

    long[] arr = new long[20];

    for(int i = 1 ; i < arr.length ; i ++){

        if ( i % 2 == 0)
        {
            arr[i] = i * arr[i - 1];
        }
        else
        {
            arr[i] = i + arr[i - 1];
        }
    }

答案 3 :(得分:0)

试试这个

public static void main(String[] args) {
    long res = 0;
    for (int i = 0; i < 20; i++) {
        if (i % 2 == 0)
            res = res * i;
        else
            res = i + res;
        System.out.println(res);
    }
}

输出

0 1 2 5 20 25 150 157 1256 1265 12650 12661 151932 151945 2127230 

答案 4 :(得分:0)

import java.lang.Math;

public class Test
{

  static long number = 0, previous = 0, limit = 100;

  public static void main(String[] args)
  {

    for (int i=1; i < limit; ++i)
    {
      System.out.print(number + " ");

      if (i % 2 != 0)
      {
          number = previous + i;
          previous = number;
      }
      else
      {
          number = previous * i;
          previous = number;
      }
    }

  }
}