[Algorithm] N numbers with an interval of X

Problem description

The method solution takes a parameter of an integer x and a natural number n and returns a list with n numbers starting from x and incrementing by x. Take a look at the following conditions and create a method solution that satisfies the conditions.

conditions

--x is an integer greater than or equal to -10000000 and less than or equal to 10000000. --n is a natural number less than or equal to 1000.

Input / output example

x n result
2 5 [2,4,6,7,10]
4 3 [4,8,12]
-4 2 [-4,-8]

Commentary


class Solution {
    public long[] solution(int x, int n) {
        long[] result = new long[n];
        result[0] = x; //Start with x, so initialize x to Index 0
        
        //Since 0 has been initialized above, i starts from 1 and repeats until n.
        for (int i = 1; i < n; i++) {
            //Since it increases by x, the result Index: i-Value of 1+Do x.
            result[i] = result[i - 1] + x;
        }
        
        return result;
    }
}

Recommended Posts

[Algorithm] N numbers with an interval of X
Convert an array of strings to numbers
[Java] Find prime numbers with an Eratosthenes sieve
[Java] Find prime numbers with an Eratosthenes sieve (Part 2)
Advantages of generating an Abstract Factory pattern with an enum
Test the contents of an Excel file with JUnit
Create an E2E test environment with Docker x Cypress