How to Print a list of numbers summed in sequence?

Asked

Viewed 926 times

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);
 }
}

inserir a descrição da imagem aqui

It seems to be all right, but actually this is not a "sequence plus".
What the program does is just add up the numbers of 2 in 2. (2+2+2+2+2)
So that way of 1 to 10 stay [2, 4, 6, 8, 10, 12, 14, 16, 18, 20].
What I really seek is a sum in sequence and not a sum of 2 in 2, or 3 in 3, or 4 in 4.

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

Equal to 2 = 2+4+6+8+10

Equal to 3 = 3+6+9+12

Equal to 4 = 4+8+12+16

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

If he were in the "added sequence" of 2.

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

If he were in the "added sequence" of 3.

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

  • You can add the code of this program that originated this problem?

  • 3

    It would be good to put the code, not a screenshot of it. You have the format tool for this in the toolbar, indicated by the icon { }

2 answers

3


The problem is that with each iteration of the 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 the 2 by an int variable representing the value of which you want this sequence summed, thus:

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.

  • It worked great Thanks!!!! @diegofm

  • @Rafaelzinho arrange! :)

0

You will need to put one more variable.

K-> the sum basis
x-> the fixed number
y-> the number that will grow 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.