Java Loops II Solution


Problem Overview

Original Problem: Java Loops II | Hackerrank

Difficulty: Easy

Category: Loops / Arithmetic Series

Description: This is an exercise in using iteration to solve an arithmetic series. We are given several queries made up of three integers. Our task is to generate and print a sequence of numbers based on a provided formula, printing each sequence on a separate line.

Understanding the Problem

We’re asked to take a given number of queries (q) and for each one generate a sequence of numbers using: a starting value (a), a multiplier (b) and the number of terms in the sequence (n). The sequence is based on this formula:

a + b * 20 + b * 21 + ... + b * 2n-1

Input:

The first line of input contains the number of queries to generate (q)

Each of the next q lines contains three integers a, b, and n where

  • 0 ≤ q ≤ 500

  • 0 ≤ a, b ≤ 50

  • 1 ≤ n ≤ 15

Output:

One sequence of numbers per query based on the provided sequence formula

Initial Reasoning

The original problem gives us template code to read each query and its three components. From here we will need to use a loop to generate each term in the sequence printing each term as it is generated and after the loop shift to the next line.

Pseudocode

// Main function:
For each query
	Read the starting value, the multiplier and the number of terms to generate
	Initialise a sum variable to store the current term
	For each term in the sequence
		Calculate the term value
		Add the value to the sum
		Print the sum to the current line and a space
 	Print a newline

Solution Code

// Note this is one of many possible solutions
import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int numQueries = scanner.nextInt();

        for (int i = 0; i < numQueries; i++) {
            int startValue = scanner.nextInt();
            int multiplier = scanner.nextInt();
            int numTerms = scanner.nextInt();

            int sum = startValue; // Initialize sum with the starting value

            for (int j = 0; j < numTerms; j++) {
                // Calculate the next term and add it to the sum
                sum +=  Math.pow(2, j) * multiplier;

                // Print the current sum
                System.out.print(sum + " ");
            }

            // After each query, move to the next line
            System.out.println();
        }

        scanner.close();
    }
}

Commenting on Alterations

While we have done our best to maintain similarity to the template code provided in the original problem, the following changes have been made to follow best practices:

  • Renamed variables:

    Using more descriptive names improves the clarity of the code and makes it easier for anyone reading the code to understand what each variable represents.