/* ACM ICPC Southeast Regional 2009 Knit Predict Author: Yiu Yu Ho Let n be the size (number of rows) of a pattern, and L[0], L[1], ..., L[n-1] be number of stitches to change in the pattern. Then, suppose before the pattern started we have a row with x stitches, then in subsequent rows we will have, in order, x+L[0], x+L[0]+L[1], x+L[0]+L[1]+L[2], ..., x+L[0]+L[1]+...+L[n-1] stitches. Let d[i] = L[0] + L[1] = ... + L[i] = sum(L[k], k = 0..i) Then, if we have a row with x stitches before the pattern starts, on the next n rows, we'll have x+d[0], x+d[1], x+d[2], ..., x+d[n-1] The sum of all n rows generated by this pattern is n*x + sum(d[i], i=0..n-1). The next set of patterns starts with new x <-- x+d[n-1], being the last row of the previous pattern. If there are q set of patterns, then the total number of stitches in these q sets (a total of q*n rows), assuming we have a row with x stitches before the start of the sets, is: sum(n*(x+k*d[n-1]) + D, k = 0 .. q-1), where D = sum(d[i], i=0..n-1) This evaluates to q*n*x + q*D + n*d[n-1]*(q-1)*q/2 */ import java.io.*; import java.util.*; public class knittingYiu { public Scanner in = new Scanner(System.in); public PrintStream out = System.out; public int L, d, D, Dr; public int x, row, n, q, r; public void main() { int i, j, k; long res; x = in.nextInt(); while(x > 0) { row = in.nextInt(); n = in.nextInt(); //q is the number of times the pattern is completely applied //r is the number of rows remaining q = (row-1)/n; r = (row-1)%n; d = D = Dr = 0; for(i=0;i