Nice Mathematical Problem

Revision en1, by M_a_h_t_a_b, 2025-11-30 08:14:27
Magical Diamond
                                                  Time Limit: 1 second
                                               Memory Limit: 256 megabytes

Problem Statement Alice discovered a Magical Diamond sequence defined by a positive integer k. The sequence is constructed as follows: 1,2,3,…,k−1,k,k−1,k−2,…,2,1 In other words, the sequence first increases from 1 to k, then decreases back to 1. The total length of the sequence is 2k−1. For a given position x in this sequence (1-based index), Alice wants to know the cumulative sum of the first x elements. Formally, define: Cumulative Sum(x) = sum of the first x elements of the sequence Help Alice calculate Cumulative Sum(x) efficiently.

Input The first and only line contains two integers k and x (1≤k≤10^9,1≤x≤2k−1) — the size of the diamond and the position for which the cumulative sum is required.

Output Print a single integer — the cumulative sum of the first x elements of the Magical Diamond sequence.

Examples Input: 4 3

Output: 6

Explanation: The sequence is: 1 2 3 4 3 2 1 Cumulative sum of the first 3 elements: 1 + 2 + 3 = 6

Tags math, implementations

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English M_a_h_t_a_b 2025-11-30 08:14:27 1284 Initial revision (published)