#C4428. Sum of First N Even or Odd Numbers
Sum of First N Even or Odd Numbers
Sum of First N Even or Odd Numbers
You are given an integer \(n\) and a boolean flag isEven
. Your task is to form an array \(nums\) of length \(n\) in which:
- If
isEven
is true, then \(nums[i]\) is the \(i\)th positive even number, i.e., \(2\times i\) for \(i=1,2,\dots,n\) (formally, \(nums = [2,4,6,\dots,2n]\)). - If
isEven
is false, then \(nums[i]\) is the \(i\)th positive odd number, i.e., \(2\times i - 1\) for \(i=1,2,\dots,n\) (formally, \(nums = [1,3,5,\dots,2n-1]\)).
Your task is to compute and output the sum of all elements in the array \(nums\). In mathematical terms, if isEven
is true you need to compute \(\sum_{i=1}^{n} 2i\), otherwise compute \(\sum_{i=1}^{n} (2i-1)\).
Note: The input will be read from standard input and the output should be written to standard output.
inputFormat
The input consists of two lines:
- The first line contains a single integer \(n\) (the number of elements).
- The second line contains a string "True" or "False" indicating whether to generate even numbers (
True
) or odd numbers (False
).
Please note that you should read from stdin
.
outputFormat
Output a single integer representing the sum of the first \(n\) even or odd numbers as described. The result should be printed to stdout
.
4
True
20