Create a numerical sequence by storing in Arraylist

Asked

Viewed 503 times

-5

I need to develop a Java algorithm that returns the following sequence:

9, 16, 25, 36, 49...

I’ve identified that the pattern is as follows:

9 = 3²
16 = 4²
25 = 5²
36 = 6²

Values need to be stored in a ArrayList and be shown at the end.

  • 1

    Where will these numbers come from? Is there an expected pattern in this sequence? What have you tried to do? See that your question continues with the same problems as the others.

  • So I want to know how this kind of algorithm works, to understand how this logic is formed

  • I’ll give you a tip on how to elaborate a question at least, acceptable here on the site, answering these questions: What do I intend to do? What have I ever tried to do? What problems am I having doing? By creating a question correctly answering this, your question will hardly be bad.

  • Figure out the logic for sequence 9, 16, 25, 36, 49. Looking for sequence algorithms.

  • Ready, edited publication.

  • Is the sequence only up to 49? The program receives some value?

  • You can go to 49. Yes, it takes the incial value int n.

  • Can you use power-ready functions like the Math class? Or everything has to be done without using ready-made classes?

  • No need to use Math class.

  • 1

    for(int i=3; i < limit; i++){ System.out.println(i*i); }

  • You can help me insert these results into an Arraylist and then print ?

Show 6 more comments

1 answer

2


Try it like this:

    int valorInicial = 3;
    int n = 7;
    ArrayList<Integer> lista = new ArrayList<>();
    // usando math
    for(int i = valorInicial; i <= n; i++){
        lista.add((int)Math.pow(i,2));
    }

    for(Integer num : lista){
        System.out.print(num + " ");
    }

or without using the class Math:

    int valorInicial = 3;
    int n = 7;
    ArrayList<Integer> lista = new ArrayList<>();
    //sem usar math
    for(int i = valorInicial; i <= n; i++){
        lista.add(i*i);
    }

    for(Integer num : lista){
        System.out.print(num + " ");
    }

In this link from ideone, you can see the result(that will be the same) of the two working methods.

  • You can help me put this on an Arraylist and then print ?

  • @Rafaelaugusto edited, see now if it meets.

Browser other questions tagged

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