Number Spiral CSES Solution

Number Spiral CSES Solution
Number Spiral CSES Solution

A number spiral is an infinite grid whose upper-left square has the number 1. Here are the first five layers of the spiral:
Your task is to find out the number in row y and column x.

Input

The first input line contains an integer tt: the number of tests.

After this, there are tt lines, each containing integers y and x.

Output

For each test, print the number in row y and column x.

Constraints

  • 1≤t≤1051≤t≤105
  • 1≤y,x≤1091≤y,x≤109

Example

Input:
3
2 3
1 1
4 2

Output:
8
1
15

Code Solution

//Number Spiral CSES Solution

// Java program to find minimum moves required
// to make the array in increasing order
import java.util.*;
import java.lang.*;
import java.io.*;
 
public class SpiralNumber{
 
static class FastReader {
        BufferedReader br;
        StringTokenizer st;
 
        public FastReader()
        {
            br = new BufferedReader(
                new InputStreamReader(System.in));
        }
 
        String next()
        {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }
 
        int nextInt() { return Integer.parseInt(next()); }
 
        long nextLong() { return Long.parseLong(next()); }
 
        double nextDouble()
        {
            return Double.parseDouble(next());
        }
 
        String nextLine()
        {
            String str = "";
            try {
                str = br.readLine();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static void main(String args[]){   
        FastReader sc = new FastReader();
        long t=sc.nextInt();
        while(t--!=0){
            long x=sc.nextInt();
            long y=sc.nextInt();
            if (x < y)
        {
            if (y % 2 == 1)
            {
                long r = y * y;
                System.out.println(r-x+1);
            }
            else
            {
                long r = (y - 1) * (y - 1) + 1;
                System.out.println(r+x-1);
            }
        }
        else
        {
            if (x % 2 == 0)
            {
                long r = x * x;
                System.out.println(r-y+1);
            }
            else
            {
                long r = (x - 1) * (x - 1) + 1;
                System.out.println(r+y-1);
            }
        }
    }
        
        
    }
}

//Number Spiral CSES Solution

Leave a Comment