How to print a list of numbers added in sequence?

1

Program:

    public static void main(String[] args) {

    List<Long> lista = new ArrayList();

    long k = 0;

    for (long a = 1; a <= 10; a++) {

    k = k+2; 

    lista.add(k);

  }  

    System.out.println("Soma="+lista);
 }
}

Itseemstobeallright,butinfactthisisnotan"added sequence". What the program does is just add the numbers from 2 to 2 . (2 + 2 + 2 + 2 + 2)
So this way from 1 to 10 are [2, 4, 6, 8, 10, 12, 14, 16, 18, 20].
What I'm really looking for is a sum in sequence and does not add from 2 to 2 , or 3 to 3 , or 4 to 4 .

Example: 1+2+3+4+5+6+7+8+9+10 (would be rising) that would be the sequence!
And not a "stop sum" (1 + 1 + 1 + 1 + 1).

Same as 2 = 2+4+6+8+10

Same as 3 = 3+6+9+12

Same as 4 = 4+8+12+16

In my program print: Sum = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20] (2 + 2 + 2 + 2 + 2, etc.)

If it were in the "added stream" of 2 .

This would be the result: Sum = [2, 6, 12, 20, 30, 42, 56, 72, 90, 110] (2 + 4 + 6 + 8 + 10, etc.)

If it were in the "added stream" of 3 .

This would be the result: Sum = [3, 9, 18, 30, 45, 63, 84, 108, 135, 165] (3 + 6 + 9 + 12 + 15, etc.)

    
asked by anonymous 14.09.2016 / 19:16

2 answers

3

The problem is that with each iteration of for, it will only add 2, and not add up according to the multiple of the base number. For this you need to increment the value by multiplying the loop and base iterator (in the case of question code, 2):

k = k + (a * 2); 

You can change 2 by an int variable that represents the value of which you want this added sequence, like this:

public static void main (String[] args) {

    List<Long> lista = new ArrayList();

    long k = 0;

    //aqui você pode trocar por outros números que quer
    //fazer a sequencia tendo ele como base
    int base = 2; 

    for (long a = 1; a <= 10; a++) {

       k += (base*a); 

       lista.add(k);
    }  

    System.out.println("Soma="+lista);
 }

See working on IDEONE .

    
14.09.2016 / 19:34
0

You'll need to add another variable.

  

K-> the base of the sum
  x- > the fixed number
  y- > the number that had grown with the fixed number

The account will look something like this (assuming x is 2):

y = 0; 
K = 0;
for(int a=0; a<=10;a++){    
   y = y+2;   //=>(x=2)  
   K = K+y;
}
    
14.09.2016 / 19:33