Soluție HackerRank pentru Summing the N series, subdomeniul Fundamentals, în C++14. Include cerința formatată, exemple, explicația pașilor și cod sursă.

  • Problemă: Summing the N series
  • Domeniu: Fundamentals
  • Limbaj: C++14

Challenge: Summing the N series

Subdomeniu: Fundamentals (fundamentals)

Scor cont: 20.0 / 20

Submission status: Accepted

Submission score: 1.0

Submission ID: 464723435

Limbaj: cpp14

Link challenge: https://www.hackerrank.com/challenges/summing-the-n-series/problem

Cerință

There is a sequence whose n^{text{th}} term is
T_n = n^2 - (n-1)^2

Evaluate the series
S_n = T_1 + T_2 + T_3 + ·s + T_n
Find S_n bmod (10^9+7).

Example

n = 3

The series is 1^2-0^2 + 2^2-1^2 + 3^2-2^2 = 1 + 3 + 5 = 9.

Function Description

Complete the *summingSeries* function in the editor below.

*summingSeries* has the following parameter(s):

- *int n:* the inclusive limit of the range to sum

Returns

- *int:* the sum of the sequence, modulo (10^9+7)

Input Format

The first line of input contains t, the number of test cases.
Each test case consists of one line containing a single integer n.

Constraints

+ 1 ≤ t ≤ 10
+ 1 ≤ n ≤ 10^16

Cod sursă

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);

int summingSeries(long n) {
return ((n%1000000007)*(n%1000000007))%1000000007;
}
int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string t_temp;
    getline(cin, t_temp);

    int t = stoi(ltrim(rtrim(t_temp)));

    for (int t_itr = 0; t_itr < t; t_itr++) {
        string n_temp;
        getline(cin, n_temp);

        long n = stol(ltrim(rtrim(n_temp)));

        int result = summingSeries(n);

        fout << result << "\n";
    }

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}
HackerRank Fundamentals – Summing the N series