A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it!

You are given integers $n,k$. Construct a grid $A$ with size $n \times n$ consisting of integers $0$ and $1$. The very important condition should be satisfied: the sum of all elements in the grid is exactly $k$. In other words, the number of $1$ in the grid is equal to $k$.

Let's define:  $A_{i,j}$ as the integer in the $i$-th row and the $j$-th column.  $R_i = A_{i,1}+A_{i,2}+...+A_{i,n}$ (for all $1 \le i \le n$).  $C_j = A_{1,j}+A_{2,j}+...+A_{n,j}$ (for all $1 \le j \le n$).  In other words, $R_i$ are row sums and $C_j$ are column sums of the grid $A$.  For the grid $A$ let's define the value $f(A) = (\max(R)-\min(R))^2 + (\max(C)-\min(C))^2$ (here for an integer sequence $X$ we define $\max(X)$ as the maximum value in $X$ and $\min(X)$ as the minimum value in $X$). 

Find any grid $A$, which satisfies the following condition. Among such grids find any, for which the value $f(A)$ is the minimum possible. Among such tables, you can find any.


-----Input-----

The input consists of multiple test cases. The first line contains a single integer $t$ ($1 \le t \le 100$) — the number of test cases. Next $t$ lines contain descriptions of test cases.

For each test case the only line contains two integers $n$, $k$ $(1 \le n \le 300, 0 \le k \le n^2)$.

It is guaranteed that the sum of $n^2$ for all test cases does not exceed $10^5$.


-----Output-----

For each test case, firstly print the minimum possible value of $f(A)$ among all tables, for which the condition is satisfied.

After that, print $n$ lines contain $n$ characters each. The $j$-th character in the $i$-th line should be equal to $A_{i,j}$.

If there are multiple answers you can print any.


-----Example-----
Input
4
2 2
3 8
1 0
4 16

Output
0
10
01
2
111
111
101
0
0
0
1111
1111
1111
1111



-----Note-----

In the first test case, the sum of all elements in the grid is equal to $2$, so the condition is satisfied. $R_1 = 1, R_2 = 1$ and $C_1 = 1, C_2 = 1$. Then, $f(A) = (1-1)^2 + (1-1)^2 = 0$, which is the minimum possible value of $f(A)$.

In the second test case, the sum of all elements in the grid is equal to $8$, so the condition is satisfied. $R_1 = 3, R_2 = 3, R_3 = 2$ and $C_1 = 3, C_2 = 2, C_3 = 3$. Then, $f(A) = (3-2)^2 + (3-2)^2 = 2$. It can be proven, that it is the minimum possible value of $f(A)$.

Difficulty: MEDIUM_HARD
Tags: Greedy algorithms

Implementation

Constructive algorithms
Skill types: Greedy algorithms

Starter code:

Solutions:
import math
t = int(input())
for _ in range(t):
	line = input().strip().split(' ')
	(n, k) = (int(line[0]), int(line[1]))
	if n ** 2 == k:
		print(0)
		for row in range(n):
			for col in range(n):
				print(1, end='')
			print('')
	elif n == k:
		print(0)
		for row in range(n):
			for col in range(n):
				if row == col:
					print(1, end='')
				else:
					print(0, end='')
			print('')
	elif k == 0:
		print(0)
		for row in range(n):
			for col in range(n):
				print(0, end='')
			print('')
	elif k % n == 0:
		print(0)
		leng = k // n
		for row in range(n):
			start = row
			rowdata = [0] * n
			for i in range(leng):
				rowdata[(start + i) % n] = 1
			for d in rowdata:
				print(d, end='')
			print('')
	else:
		print(2)
		leng = k // n
		diff = k - leng * n
		for row in range(n):
			start = row
			rowdata = [0] * n
			for i in range(leng):
				rowdata[(start + i) % n] = 1
			if row < diff:
				rowdata[(start + leng) % n] = 1
			for d in rowdata:
				print(d, end='')
			print('')


t = int(input())
for q in range(t):
	(n, k) = map(int, input().split())
	(x, y) = (0, 0)
	nch = 0
	u = 0
	ans = [[0] * n for i in range(n)]
	while nch < n and u < k:
		if nch == 0:
			x = 0
			y = 0
			while x < n and u < k:
				ans[x][y] = 1
				x += 1
				y += 1
				u += 1
			nch += 1
		else:
			x = nch
			y = 0
			while y < n and u < k:
				ans[x][y] = 1
				x += 1
				y += 1
				u += 1
				if x == n:
					x = 0
			y = nch
			x = 0
			while x < n and u < k:
				ans[x][y] = 1
				x += 1
				y += 1
				u += 1
				if y == n:
					y = 0
			nch += 1
	rma = 0
	rmi = 1000000000000000000000
	cma = 0
	cmi = 1000000000000000000000
	for i in range(n):
		l = sum(ans[i])
		rma = max(l, rma)
		rmi = min(l, rmi)
	for j in range(n):
		su = 0
		for i in range(n):
			su += ans[i][j]
		cma = max(su, cma)
		cmi = min(cmi, su)
	print((rma - rmi) ** 2 + (cma - cmi) ** 2)
	for i in range(n):
		for j in range(n):
			print(ans[i][j], end='')
		print()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = 0
	a = k // n * n
	b = k % n
	if k < n and k != 0:
		ans = 2
	elif b > 0:
		ans = 2
	else:
		ans = 0
	mat = [[0] * n for i in range(n)]
	total = 0
	t = 0
	while total < k:
		(x, y) = (0, t)
		for i in range(n):
			mat[x][y] = 1
			total += 1
			if total == k:
				break
			x = (x + 1) % n
			y = (y + 1) % n
		t += 1
	print(ans)
	for i in range(n):
		print(''.join(map(str, mat[i])))


import sys, math
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().split()]

def getInt():
	return int(input())

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())
import collections as col
import math

def solve():
	(N, K) = getInts()
	M = [[0 for m in range(N)] for n in range(N)]
	(q, r) = (K // N, K % N)
	arr = [q] * (N - r) + [q + 1] * r
	if r == 0:
		print(0)
	else:
		print(2)
	start = 0
	for n in range(N):
		val = arr.pop()
		for j in range(start, start + val):
			M[n][j % N] = 1
		start = (start + val) % N
		print(*M[n], sep='')
for t in range(getInt()):
	solve()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = k // n
	rem = k % n
	grid = []
	for i in range(n):
		grid.append([])
		for j in range(n):
			grid[-1].append('0')
	for i in range(n):
		for j in range(i, i + a):
			grid[i][j % n] = '1'
		if i < rem:
			grid[i][(i + a) % n] = '1'
	ans = 0
	r = []
	for i in range(n):
		p = 0
		for j in range(n):
			if grid[i][j] == '1':
				p += 1
		r.append(p)
	c = []
	for i in range(n):
		p = 0
		for j in range(n):
			if grid[j][i] == '1':
				p += 1
		c.append(p)
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in range(n):
		ans = ''.join(grid[i])
		print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = [[0 for i in range(n)] for j in range(n)]
	i = 0
	j = 0
	while i < k:
		x = 0
		y = j
		while x < n and i < k:
			ans[x][y] = 1
			i += 1
			x += 1
			y = (y + 1) % n
		j += 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for j in ans:
		print(''.join((str(x) for x in j)))


import os, sys, atexit
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
_OUTPUT_BUFFER = StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
t = int(input())
while t:
	t += -1
	(n, k) = map(int, input().split())
	ans = []
	for i in range(n):
		ans.append([0] * n)
	(cnt, start) = (0, 0)
	while 1:
		tmp = start
		for i in range(n):
			if k == 0:
				break
			ans[i][tmp % n] = 1
			tmp -= -1
			k += -1
		start -= -1
		if k == 0:
			break
	(mnro, mncol, mxro, mxcol) = (999999999999, 999999999999, 0, 0)
	for i in ans:
		tmp = sum(i)
		mnro = min(mnro, tmp)
		mxro = max(mxro, tmp)
	for i in range(n):
		sm = 0
		for j in range(n):
			sm += ans[j][i]
		mncol = min(mncol, sm)
		mxcol = max(mxcol, sm)
	print((mxro - mnro) * (mxro - mnro) + (mxcol - mncol) * (mxcol - mncol))
	for i in ans:
		print(*i, sep='')


def mi():
	return map(int, input().split())
for _ in range(int(input())):
	(n, k) = mi()
	print(2 * (k % n != 0))
	a = [[0] * n for i in range(n)]
	(i, j) = (0, 0)
	for __ in range(k):
		a[i][j] = 1
		i += 1
		j += 1
		if i == n:
			j += 1
		i %= n
		j %= n
	for i in a:
		for j in i:
			print(j, end='')
		print()


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	(n, k) = MI()
	if k % n != 0:
		print(2)
	else:
		print(0)
	l = []
	for i in range(n):
		l.append(['0'] * n)
	for i in range(n):
		for j in range(n):
			if k <= 0:
				break
			else:
				l[j][(j + i) % n] = '1'
				k -= 1
	for i in range(n):
		print(''.join(l[i]))


import sys, math, os
from io import BytesIO, IOBase
from collections import defaultdict as dd, deque, Counter

def data():
	return sys.stdin.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 9
mod = 998244353
for t in range(int(data())):
	(n, k) = mdata()
	mat = [[0] * n for i in range(n)]
	i = 0
	cnt1 = 0
	cnt2 = 0
	while cnt1 < k:
		for j in range(n):
			mat[j][i] = 1
			cnt1 += 1
			if cnt1 == k:
				break
			i = (i + 1) % n
		i = (i + 1) % n
	ans = 2 * (0 if k % n == 0 else 1)
	out(ans)
	for i in range(n):
		mat[i] = ''.join(map(str, mat[i]))
	out('\n'.join(mat))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0] * n for _ in range(n)]
	b = []
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		if k == 0:
			break
		else:
			a[i][i] = 1
			k -= 1
	j = 1
	while j < n:
		if k > 0:
			for i in range(j, n):
				if k == 0:
					break
				else:
					a[i - j][i] = 1
					k -= 1
		if k > 0:
			for i in range(j):
				if k == 0:
					break
				else:
					a[n - j + i][i] = 1
					k -= 1
		if k > 0:
			j += 1
		else:
			break
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def L():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
t = 1
t = int(input())
for _ in range(t):
	(n, k) = L()
	A = [[0 for i in range(n)] for j in range(n)]
	p = q = 0
	for i in range(k):
		A[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	rmax = cmax = 0
	rmin = cmin = 10 ** 10
	for i in range(n):
		x = [A[i][j] for j in range(n)]
		rmin = min(rmin, sum(x))
		rmax = max(rmax, sum(x))
		cmin = min(cmin, sum(A[i]))
		cmax = max(cmax, sum(A[i]))
	print((rmin - rmax) ** 2 + (cmin - cmax) ** 2)
	for i in range(n):
		for j in range(n):
			print(A[i][j], end='')
		print()


def display(arr):
	for i in range(n):
		for j in range(n):
			print(arr[i][j], end='')
		print()
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = [[0 for i in range(n)] for i in range(n)]
	(p, q) = (0, 0)
	i = 0
	while i <= k - 1:
		arr[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
		i += 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	display(arr)


from collections import deque, defaultdict
from math import sqrt, ceil, factorial, floor, inf, log2, sqrt, gcd
import bisect
import sys
import copy

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def input():
	return sys.stdin.readline().strip()
for _ in range(int(input())):
	(n, k) = get_ints()
	arr = [[0 for i in range(n)] for j in range(n)]
	i = 0
	while i != n and k > 0:
		arr[i][i] = 1
		i += 1
		k -= 1
	(sti, stj) = (0, 1)
	(stp, stq) = (n - 1, 0)
	while k > 0 and stj <= n - 1 and (stp > 0):
		(i, j) = (sti, stj)
		(p, q) = (stp, stq)
		while k > 0 and i <= n - 1 and (j <= n - 1):
			arr[i][j] = 1
			i += 1
			j += 1
			k -= 1
		while k > 0 and p <= n - 1 and (q <= n - 1):
			arr[p][q] = 1
			p += 1
			q += 1
			k -= 1
		stj += 1
		stp -= 1
	a1 = []
	for i in range(len(arr)):
		a1.append(sum(arr[i]))
	a2 = []
	for j in range(n):
		sumi = 0
		for i in range(n):
			sumi += arr[i][j]
		a2.append(sumi)
	a1.sort()
	a2.sort()
	ans = (a1[n - 1] - a1[0]) ** 2 + (a2[n - 1] - a2[0]) ** 2
	print(ans)
	for i in range(n):
		for j in range(n):
			arr[i][j] = str(arr[i][j])
	for i in range(n):
		print(''.join(arr[i]))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	f = 2
	if k % n == 0:
		f = 0
	l = [['0' for i in range(n)] for j in range(n)]
	no = k
	y = 0
	for w in range(n):
		x = 0
		y = w
		for j in range(n):
			if no == 0:
				break
			no -= 1
			l[x][y % n] = '1'
			x += 1
			y += 1
		if no == 0:
			break
	print(f)
	for k in l:
		print(''.join(k))


def readintlst():
	return list(map(int, input().split(' ')))

def readcharlst():
	return list(input().split(' '))

def readn():
	return int(input())
for _ in range(readn()):
	(n, k) = readintlst()
	mat = [[0] * n for _ in range(n)]
	i = j = 0
	kk = k
	while k:
		k -= 1
		mat[i][j] = 1
		i += 1
		j += 1
		if i == n:
			i = 0
			j += 1
		j %= n
	ans = 0 if kk % n == 0 else 2
	print(ans)
	for r in mat:
		print(''.join(map(str, r)))


import sys
lines = sys.stdin.readlines()
T = int(lines[0].strip())
for t in range(T):
	(a, b) = map(int, lines[t + 1].strip().split(' '))
	res = [[0 for _ in range(a)] for _ in range(a)]
	rema = b % a
	deno = b // a
	if rema == 0:
		val = 0
	else:
		val = 2
	for i in range(a):
		if i < rema:
			for j in range(deno + 1):
				res[i][(i + j) % a] = 1
		else:
			for j in range(deno):
				res[i][(i + j) % a] = 1
	print(val)
	for i in range(a):
		print(''.join(map(str, res[i])))


from queue import PriorityQueue
test_case = int(input())
for _ in range(test_case):
	(size, k) = map(int, input().split())
	if size ** 2 == k:
		print('0')
		for i in range(size):
			print('1' * size)
	elif k == 0:
		print('0')
		for i in range(size):
			print('0' * size)
	else:
		board = [[False for i in range(size)] for j in range(size)]
		for i in range(size):
			for j in range(size):
				if k > 0:
					board[(i + j) % size][j] = True
					k -= 1
		(row, col) = ([], [])
		for i in range(size):
			count = 0
			for j in range(size):
				if board[j][i]:
					count += 1
			col.append(count)
		for i in range(size):
			row.append(board[i].count(True))
		print((max(row) - min(row)) ** 2 + (max(col) - min(col)) ** 2)
		for i in range(size):
			for j in range(size):
				if board[i][j]:
					print('1', end='')
				else:
					print('0', end='')
			print()


for _ in range(int(input())):
	(n, k) = map(int, input().split(' '))
	A = [[0 for i in range(n)] for j in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		for j in range(n):
			x = j
			y = (i + j) % n
			if k == 0:
				break
			else:
				A[x][y] = 1
				k = k - 1
	for i in range(n):
		for j in range(n):
			print(A[i][j], end='')
		print()


t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	if k == n * n:
		print(0)
		for i in range(n):
			for j in range(n):
				print(1, end='')
			print()
	else:
		p = k % n
		if p == 0:
			print(0)
		else:
			print(2)
		for i in range(n):
			for j in range(n):
				if i == j and i < p:
					print(1, end='')
				elif i != j and (j - i + n) % n <= k // n:
					print(1, end='')
				else:
					print(0, end='')
			print()


for i in range(int(input())):
	(n, k) = map(int, input().split())
	if k == 0:
		lo = n
		print(0)
		while lo:
			s = '0' * n
			print(s)
			lo -= 1
	elif k < n:
		fa = 2
		c = 0
		print(fa)
		lo = n
		while lo:
			if k:
				s = '0' * c + '1' + '0' * (n - c - 1)
				c += 1
				k -= 1
			else:
				s = '0' * n
			lo -= 1
			print(s)
	elif k == n:
		fa = 0
		c = 0
		print(fa)
		lo = n
		while lo:
			s = '0' * c + '1' + '0' * (n - c - 1)
			c += 1
			lo -= 1
			print(s)
	else:
		maxi = k // n
		mini = k // n
		rem = k % n
		if rem != 0:
			maxi += 1
		fa = 2 * (maxi - mini) ** 2
		c = 0
		if rem != 0:
			maxi -= 1
		print(fa)
		while c != n:
			l = ['0' if i != c else '1' for i in range(n)]
			if rem:
				c1 = maxi
				rem -= 1
			else:
				c1 = maxi - 1
			c2 = c
			while c1:
				if c2 + 1 < n:
					c2 += 1
				else:
					c2 = 0
				l[c2] = '1'
				c1 -= 1
			print(''.join(l))
			c += 1


def solu(n, k):
	r = 2 if k % n else 0
	a = cr_matrix(n, 0)
	remain = k
	if k == 0:
		return (r, a)
	(i, j) = (0, 0)
	d = 1
	while remain > 0:
		a[i][j] = 1
		remain -= 1
		if j == n - 1 and i == n - 1:
			i = 0
			j = 1
		elif j == n - 1:
			i += 1
			j = 0
		elif i == n - 1:
			i = 0
			j += 2
		else:
			i += d
			j += d
	return (r, a)

def cr_matrix(n, p):
	matrix = [[p] * n for i in range(n)]
	return matrix
nt = int(input())
for i in range(nt):
	test = input().split(' ')
	n = int(test[0])
	k = int(test[1])
	result = solu(n, k)
	print(result[0])
	for r in range(n):
		row = ''.join((str(v) for v in result[1][r]))
		print(row)


import sys
INF = 10 ** 18
MOD = 10 ** 9 + 7
input = lambda : sys.stdin.readline().rstrip()
YesNo = lambda b: bool([print('Yes')] if b else print('No'))
YESNO = lambda b: bool([print('YES')] if b else print('NO'))
int1 = lambda x: int(x) - 1
T = int(input())
for _ in range(T):
	(N, K) = map(int, input().split())
	c = [[0] * N for _ in range(N)]
	(y, x) = (0, 0)
	n = 1
	for i in range(K):
		c[y][x] = 1
		x += 1
		y += 1
		if x >= N:
			x -= N
		if y >= N:
			y = 0
			x = n
			n += 1
	ans = 0
	MIN = INF
	MAX = 0
	for i in range(N):
		SUM = sum(c[i])
		MIN = min(MIN, SUM)
		MAX = max(MAX, SUM)
	ans += (MAX - MIN) ** 2
	MIN = INF
	MAX = 0
	for i in range(N):
		SUM = 0
		for j in range(N):
			SUM += c[j][i]
		MIN = min(MIN, SUM)
		MAX = max(MAX, SUM)
	ans += (MAX - MIN) ** 2
	print(ans)
	for row in c:
		for a in row:
			print(a, end='')
		print('')


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]
for _ in range(val()):
	(n, k) = li()
	l = [[0 for i in range(n)] for j in range(n)]
	he1 = []
	he2 = []
	rows = [0] * n
	cols = [0] * n
	for i in range(n):
		heappush(he1, [0, i])
		heappush(he2, [0, i])
	while k:
		k -= 1
		(su1, i) = heappop(he1)
		(su2, j) = heappop(he2)
		rows[i] += 1
		cols[j] += 1
		heappush(he1, [su1 + 1, i])
		heappush(he2, [su2 + 1, j])
	for i in range(n):
		he2[i][0] *= -1
	heapify(he2)
	he3 = []
	ans = (max(rows) - min(rows)) ** 2 + (max(cols) - min(cols)) ** 2
	for i in range(n):
		he3 = []
		while rows[i]:
			rows[i] -= 1
			(su, j) = heappop(he2)
			su += 1
			l[i][j] = 1
			if su:
				heappush(he3, [su, j])
		he2.extend(he3)
		heapify(he2)
	print(ans)
	for i in l:
		print(*i, sep='')


for tc in range(int(input())):
	(n, k) = input().split(' ')
	(n, k) = (int(n), int(k))
	if k == 0 or k % n == 0:
		print(0)
		a = int(k / n)
		A = []
		for i in range(n):
			A.append([0] * n)
			for j in range(i, i + a):
				A[i][j % n] = 1
			for j in range(n):
				print(A[i][j], end='')
			print()
	else:
		print(2)
		a = int(k / n)
		b = k % n
		A = []
		for i in range(n):
			A.append([0] * n)
			for j in range(i, i + a):
				A[i][j % n] = 1
			if i < b:
				A[i][(i + a) % n] = 1
			for j in range(n):
				print(A[i][j], end='')
			print()


def read_list():
	return list(map(int, input().strip().split(' ')))

def print_list(l):
	print(''.join(map(str, l)))
N = int(input())
for _ in range(N):
	(n, k) = read_list()
	if k % n == 0:
		print(0)
	else:
		print(2)
	(s, r) = (k // n, k % n)
	for t in range(n):
		dp = [0] * n
		mm = s
		if t < r:
			mm += 1
		for i in range(mm):
			dp[(t + i) % n] = 1
		print_list(dp)


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	(n, k) = MI()
	ans = [[0 for i in range(n)] for j in range(n)]
	(i, j) = (0, 0)
	for c in range(k):
		ans[i][j] = 1
		i += 1
		j += 1
		j %= n
		if i == n:
			i = 0
			j += 1
			j %= n
	print(2 if k % n else 0)
	for i in range(n):
		print(''.join(map(str, ans[i])))


for _ in range(int(input())):
	(a, b) = map(int, input().split())
	z = [[0 for i in range(a)] for i in range(a)]
	if b > a:
		for i in range(a):
			z[i][i] = 1
		(w, r, b) = (1, a - 1, b - a)
		while b > 0:
			(q, t) = (0, 0)
			for i in range(w, a):
				z[i][q] = 1
				q += 1
				b -= 1
				if b == 0:
					break
			w += 1
			if b > 0:
				for j in range(r, a):
					z[t][j] = 1
					t += 1
					b -= 1
					if b == 0:
						break
				r -= 1
	else:
		for i in range(b):
			z[i][i] = 1
	ans = ''
	q = [[z[j][i] for i in range(a)] for j in range(a)]
	(n, m, o, p) = (float('inf'), -float('inf'), float('inf'), -float('inf'))
	for i in z:
		n = min(sum(i), n)
		m = max(sum(i), m)
	for j in q:
		o = min(sum(j), o)
		p = max(sum(j), p)
	print((m - n) ** 2 + (p - o) ** 2)
	for i in z:
		print(*i, sep='')


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	sta = 0
	a = n - k // n
	v = k % n
	for x in range(n):
		ar = [1] * n
		if x == n - v:
			a -= 1
		for y in range(a):
			ar[(sta + y) % n] = 0
		sta += 1
		print(''.join((str(i) for i in ar)))


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f():
	(n, k) = [int(s) for s in input().split()]
	M = [[0] * n for _ in range(n)]
	a = k // n
	for i in range(n):
		for j in range(i + 1 - a, i + 1):
			M[i][j] = 1
	if k % n:
		ans = 2
		for j in range(k % n):
			if a + j >= n:
				i = a + j - n
			else:
				i = a + j
			M[i][j] = 1
	else:
		ans = 0
	print(ans)
	for row in M:
		print(''.join((str(num) for num in row)))
for t in range(int(input())):
	f()


import sys
import math as mt
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = [[0 for j in range(n)] for i in range(n)]
	for i in range(n):
		if k > 0:
			k -= 1
			a[i][i] = 1
	cnt = 0
	(ux, uy, dx, dy) = (0, 1, n - 1, 0)
	while k > 0:
		if cnt % 2 == 0:
			i = ux
			j = uy
			while i < n and j < n and (k > 0):
				k -= 1
				a[i][j] = 1
				i += 1
				j += 1
			uy += 1
		else:
			i = dx
			j = dy
			while i < n and j < n and (k > 0):
				k -= 1
				a[i][j] = 1
				i += 1
				j += 1
			dx -= 1
		cnt += 1
	(rmax, rmin) = (0, n)
	(cmax, cmin) = (0, n)
	for i in range(n):
		rmax = max(sum(a[i][:]), rmax)
		rmin = min(sum(a[i][:]), rmin)
	for j in range(n):
		suma = 0
		for i in range(n):
			suma += a[i][j]
		cmax = max(suma, cmax)
		cmin = min(suma, cmin)
	print((cmax - cmin) ** 2 + (rmax - rmin) ** 2)
	for i in range(n):
		print(*a[i], sep='')


from sys import stdin, stdout
import math
input = stdin.readline

def print(x='', y='', end='\n'):
	if y == '':
		stdout.write(str(x) + end)
	else:
		stdout.write(str(x) + ' ' + str(y) + end)

def solve():
	(n, k) = map(int, input().split())
	mat = [[0] * n for i in range(n)]
	(i, j) = (0, 0)
	while k:
		mat[i % n][j % n] = 1
		i += 1
		j += 1
		k -= 1
		if not i % n:
			j += 1
	r = []
	c = []
	for i in range(n):
		ans = 0
		for j in range(n):
			if mat[i][j] == 1:
				ans += 1
		r.append(ans)
	for i in range(n):
		ans = 0
		for j in range(n):
			if mat[j][i] == 1:
				ans += 1
		c.append(ans)
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print()
tt = 1
tt = int(input())
for __ in range(tt):
	solve()


t = int(input())
for q in range(t):
	(n, k) = [int(i) for i in input().split(' ')]
	a = [[0 for i in range(n)] for j in range(n)]
	j_sm = 0
	m = 0
	while k > 0:
		for i in range(n):
			if k > 0:
				k -= 1
				a[i][(i + j_sm) % n] = 1
			else:
				m = 2
				break
		j_sm += 1
	print(m)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = [[int(0) for _ in range(n)] for _ in range(n)]
	(i, j) = (0, 0)
	for _ in range(k):
		arr[i][j] = int(1)
		i += 1
		j += 1
		if i == j == n:
			i = 0
			j = 1
		elif i == n:
			i = 0
			j += 1
		elif j == n:
			j = 0
	row_count = [int(0) for _ in range(n)]
	col_count = [int(0) for _ in range(n)]
	for i in range(n):
		for j in range(n):
			row_count[i] += arr[i][j]
			col_count[j] += arr[i][j]
	f = (max(row_count) - min(row_count)) ** 2 + (max(col_count) - min(col_count)) ** 2
	print(f)
	[print(''.join(map(str, row))) for row in arr]


def main():
	(n, k) = map(int, input().split())
	in_line = k // n
	left = k % n
	matrix = [[0 for _ in range(n)] for _ in range(n)]
	for i in range(n):
		for k in range(in_line):
			matrix[i][(i + k) % n] = 1
	for i in range(left):
		matrix[i][(i + in_line) % n] = 1
	if left == 0:
		print(0)
	else:
		print(2)
	for i in matrix:
		for k in i:
			print(k, end='')
		print()
t = int(input())
for i in range(t):
	main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print('0')
	else:
		print('2')
	a = [['0' for i in range(n)] for j in range(n)]
	for i in range(n):
		for j in range(n):
			if k == 0:
				break
			a[j][(i + j) % n] = '1'
			k -= 1
		if k == 0:
			break
	for i in range(n):
		print(''.join(a[i]))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print('0')
	else:
		print('2')
	a = []
	for i in range(n):
		a.append([0] * n)
	z = 0
	for i in range(n):
		for j in range(n):
			if k > 0:
				if i + j >= n:
					t = i + j - n
				else:
					t = i + j
				a[t][j] = 1
				k -= 1
			else:
				z = 1
				break
		if z == 1:
			break
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


import sys
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

def solve():
	(n, k) = I()
	ans = [[0] * n for i in range(n)]
	F = 0
	cur = [[0, 0]]
	(row, col) = (1, 1)
	for i in range(1, n):
		cur.append([0, col])
		col += 1
	idx = 0
	while k:
		(i, j) = cur[idx]
		while k and i < n and (j < n):
			ans[i][j] = 1
			k -= 1
			i += 1
			j += 1
			j %= n
		idx += 1
	mx = -INF
	mn = INF
	for i in range(n):
		ok = sum(ans[i])
		mx = max(mx, ok)
		mn = min(mn, ok)
	F = (mx - mn) ** 2
	mx = -INF
	mn = INF
	for i in range(n):
		ok = 0
		for j in range(n):
			ok += ans[j][i]
		mx = max(mx, ok)
		mn = min(mn, ok)
	F += (mx - mn) ** 2
	print(F)
	for i in ans:
		print(*i, sep='')
(t,) = I()
while t:
	t -= 1
	solve()


T = int(input())
for _ in range(T):
	(N, K) = map(int, input().split(' '))
	ret = [['0' for _ in range(N)] for _ in range(N)]
	for i in range(K):
		(x, y) = (i // N, i % N)
		ret[y][(x + y) % N] = '1'
	r = [sum((ret[i][j] == '1' for j in range(N))) for i in range(N)]
	c = [sum((ret[i][j] == '1' for i in range(N))) for j in range(N)]
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for row in ret:
		print(''.join(row))


for z in range(int(input())):
	(n, k) = list(map(int, input().split()))
	arr = [[0 for i in range(n)] for i in range(n)]
	c = 0
	s = [0, 0]
	while k != 0:
		arr[s[0]][s[1]] = 1
		s[0] = (s[0] + 1) % n
		s[1] = (s[1] + 1) % n
		c += 1
		if c == n:
			c = 0
			s[1] = (s[1] + 1) % n
		k -= 1
	(min_c, max_c) = (n, 0)
	for i in range(n):
		col = 0
		for j in range(n):
			if arr[j][i]:
				col += 1
		if col < min_c:
			min_c = col
		if col > max_c:
			max_c = col
	(min_r, max_r) = (n, 0)
	for i in range(n):
		row = 0
		for j in range(n):
			if arr[i][j]:
				row += 1
		if row < min_r:
			min_r = row
		if row > max_r:
			max_r = row
	print((max_c - min_c) ** 2 + (max_r - min_r) ** 2)
	for i in arr:
		for j in i:
			print(j, end='')
		print()


for t in range(int(input())):
	(n, k) = map(int, input().split())
	a = k // n
	b = k % n
	c = 0
	if b == 0:
		print('0')
	else:
		print('2')
	for i in range(n):
		d = a
		if i < b:
			d = a + 1
		if n > c + d:
			s = '0' * c + '1' * d + '0' * (n - c - d)
			c += d
		else:
			s = '1' * (c + d - n) + '0' * (n - d) + '1' * (n - c)
			c += d - n
		print(s)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	grid = [[0] * n for ___ in range(n)]
	(i, j) = (0, 0)
	while k:
		grid[i][j] = 1
		i += 1
		j = (j + 1) % n
		if i == n:
			i = 0
			j = (j + 1) % n
		k -= 1
	print((sum(grid[0]) - sum(grid[-1])) ** 2 + (sum((row[j - 1] for row in grid)) - sum((row[j] for row in grid))) ** 2)
	print(*[''.join((str(el) for el in row)) for row in grid], sep='\n')


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n, k) = I()
	an = [['0'] * n for i in range(n)]
	st = [0, 0]
	r = c = 1
	if k % n == 0 and k != 0:
		print(0)
		a = '1' * (k // n) + '0' * (n - k // n)
		for i in range(n):
			print(a)
			a = a[-1] + a[:n - 1]
		continue
	fi = 0
	a = '1' * (k // n) + '0' * (n - k // n)
	for i in range(n):
		an[i] = list(a)
		a = a[-1] + a[:n - 1]
	f = k % n
	to = n - k // n
	cur = n - to
	for i in range(n):
		if f == 0:
			break
		if '0' in an[i]:
			an[i][cur] = '1'
			f -= 1
			cur = (cur + 1) % n
	ma = 0
	mi = n + 1
	for i in range(n):
		ma = max(ma, an[i].count('1'))
		mi = min(mi, an[i].count('1'))
	fi += (ma - mi) ** 2
	ma = 0
	mi = n + 1
	for j in range(n):
		x = 0
		for i in range(n):
			if an[i][j] == '1':
				x += 1
		ma = max(ma, x)
		mi = min(mi, x)
	fi += (ma - mi) ** 2
	print(fi)
	for i in an:
		print(''.join(i))


for _ in range(int(input())):
	(n, k) = map(int, input().strip().split(' '))
	box = [[0 for i in range(n)] for j in range(n)]
	i = 0
	j = 0
	rc = [0 for i in range(n)]
	cc = [0 for i in range(n)]
	while k > 0:
		k -= 1
		box[i][j] = 1
		rc[i] += 1
		cc[i] += 1
		i += 1
		j += 1
		j %= n
		if i == n:
			i = 0
			j += 1
			j %= n
	(rmax, rmin) = (max(rc), min(rc))
	(cmax, cmin) = (max(cc), min(cc))
	ans = (rmax - rmin) ** 2 + (cmax - cmin) ** 2
	print(ans)
	for b in box:
		for a in b:
			print(a, end='')
		print()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	h = [[0] * n for i in range(n)]
	(p, q) = (0, 0)
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	for j in range(k):
		h[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	print('')
	print(ans)
	for j in range(n):
		print('')
		for o in range(n):
			print(h[j][o], end='')


nb_cases = int(input())
for case in range(nb_cases):
	(n, k) = [int(x) for x in input().split()]
	if k % n == 0:
		print(0)
	else:
		print(2)
	matrice = [['0' for j in range(n)] for i in range(n)]
	for x in range(k):
		matrice[x % n][(x % n + x // n) % n] = '1'
	for i in range(n):
		for j in range(n):
			print(matrice[i][j], end='')
		print('')


import math
import sys
t = int(input())
result = []
for cs in range(t):
	(n, k) = map(int, input().split())
	a = [[0] * n for _ in range(n)]
	result.append('0' if k % n == 0 else '2')
	for i in range(n):
		cur = 0
		while cur < n and k > 0:
			a[cur][(i + cur) % n] = 1
			k -= 1
			cur += 1
	for i in range(n):
		result.append(''.join(map(str, a[i])))
print('\n'.join(result))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	k1 = k
	g = [['0' for i in range(n)] for j in range(n)]
	l = [i for i in range(n)]
	i = 0
	while k > 0:
		g[i][l[i]] = '1'
		l[i] = (l[i] + 1) % n
		i = (i + 1) % n
		k -= 1
	if k1 % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(g[i]))


num = int(input())
for _ in range(num):
	(a, b) = map(int, input().split())
	arr = [[0 for i in range(a)] for j in range(a)]
	ans = 0
	i = 0
	j = 0
	ev = 2
	w = a - 1
	while i < a:
		while i < a and j < a:
			if ans == b:
				break
			else:
				arr[i][j] = 1
				ans += 1
			i += 1
			j += 1
		if ans == b:
			break
		if i == a and j == a:
			i = 1
			j = 0
		elif i == a and j != a:
			i = 0
			j = w
			w -= 1
		elif i != a and j == a:
			i = ev
			j = 0
			ev += 1
	if b % a == 0:
		print('0')
	else:
		print('2')
	for i in range(a):
		for j in range(a):
			print(arr[i][j], end='')
		print()


from sys import *
input = stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = []
	for i in range(n):
		b = [0] * n
		a.append(b)
	cn = (n - 1) * 2
	for i in range(n):
		if k == 0:
			break
		k -= 1
		a[i][i] = 1
	r = cn
	while k > 0:
		if cn % 2 == 0:
			i = 0
			j = (r - cn) // 2 + 1
			cn -= 1
			while k > 0 and j < n:
				a[i][j] = 1
				k -= 1
				i += 1
				j += 1
		else:
			t = n - ((r - cn) // 2 + 1) - 1
			i = n - 1
			j = (r - cn) // 2
			cn -= 1
			while k > 0 and i > t:
				a[i][j] = 1
				k -= 1
				i -= 1
				j -= 1
	(mxr, mnr) = (0, 1e+18)
	for i in range(n):
		sn = 0
		for j in range(n):
			sn += a[j][i]
		mxr = max(mxr, sn)
		mnr = min(mnr, sn)
	(mxc, mnc) = (0, 1e+18)
	for i in range(n):
		sn = 0
		for j in range(n):
			sn += a[i][j]
		mxc = max(mxc, sn)
		mnc = min(mnc, sn)
	f = (mxc - mnc) ** 2 + (mxr - mnr) ** 2
	stdout.write(str(f) + '\n')
	for i in range(n):
		for j in range(n):
			stdout.write(str(a[i][j]) + '')
		stdout.write('\n')


def read_line(type=int):
	return list(map(type, input().split()))

def sum_from_1_to_(i):
	return i * (i + 1) // 2

def is_odd(a):
	return a % 2 == 0

def print_table(table):
	for row in table:
		print(' '.join(row))

def gcd(a, b):
	while a != 0 and b != 0:
		if a > b:
			a %= b
		else:
			b %= a
	return a + b
t = int(input())
for _ in range(t):
	(n, k) = read_line()
	print(k % n and 2)
	i = n
	while i:
		i -= 1
		s = ((k + i) // n * '1').zfill(n)
		print(s[i:] + s[:i])


import math
import collections
import sys

def inpu():
	return input().split(' ')

def inti(a):
	for i in range(len(a)):
		a[i] = int(a[i])
	return a

def inp():
	a = inpu()
	a = inti(a)
	return a
for _ in range(int(input())):
	a = inp()
	(n, k) = (a[0], a[1])
	val = k
	a = []
	for i in range(n):
		a.append([0] * n)
	init = 0
	maxrow = 0
	maxcol = 0
	while k > 0:
		for i in range(n):
			a[i][(i + init) % n] = 1
			k -= 1
			if k <= 0:
				break
		init += 1
	if val % n != 0:
		print(2)
	else:
		print(0)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


q = int(input())
for qq in range(q):
	s = input().split()
	n = int(s[0])
	k = int(s[1])
	a = [[0 for i in range(n)] for j in range(n)]
	for i in range(min(k, n)):
		a[i][i] = 1
		k -= 1
	start = 1
	while k > 0:
		i = start
		j = 0
		while k > 0 and i < n:
			a[i][j] = 1
			k -= 1
			i += 1
			j += 1
		i = 0
		j = n - start
		while k > 0 and j < n:
			a[i][j] = 1
			k -= 1
			i += 1
			j += 1
		i = 0
		j = start
		while k > 0 and j < n:
			a[i][j] = 1
			k -= 1
			i += 1
			j += 1
		i = n - start
		j = 0
		while k > 0 and i < n:
			a[i][j] = 1
			k -= 1
			i += 1
			j += 1
		start += 1
	minn = n + 1
	maxx = 0
	for i in range(n):
		s = 0
		for j in range(n):
			s += a[i][j]
		minn = min(minn, s)
		maxx = max(maxx, s)
	R = (maxx - minn) * (maxx - minn)
	minn = n + 1
	maxx = 0
	for i in range(n):
		s = 0
		for j in range(n):
			s += a[j][i]
		minn = min(minn, s)
		maxx = max(maxx, s)
	C = (maxx - minn) * (maxx - minn)
	print(C + R)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
cases = int(input())
for t in range(cases):
	(n, k) = list(map(int, input().split()))
	if k % n == 0:
		print(0)
	else:
		print(2)
	a = [['1'] * n for i in range(n)]
	d = {i: i for i in range(n)}
	for i in range(n ** 2 - k):
		row = i % n
		col = d[row]
		d[row] = (col + 1) % n
		a[row][col] = '0'
	for i in a:
		print(''.join(i))


n = int(input())
for i in range(0, n):
	(n, m) = map(int, input().split())
	if m % n == 0:
		print(0)
	else:
		print(2)
	for i in range(0, m % n):
		if i + m // n + 1 <= n:
			print('0' * i + '1' * (m // n + 1) + '0' * (n - m // n - 1 - i))
		else:
			print('1' * (i + m // n + 1 - n) + '0' * (n - m // n - 1) + '1' * (n - i))
	for i in range(m % n, n):
		if i + m // n <= n:
			print('0' * i + '1' * (m // n) + '0' * (n - m // n - i))
		else:
			print('1' * (i + m // n - n) + '0' * (n - m // n) + '1' * (n - i))


tests = int(input())
for _ in range(tests):
	(n, k) = map(int, input().split())
	if k == 0:
		print(0)
		for i in range(n):
			print('0' * n)
		continue
	if k % n == 0:
		print(0)
	else:
		print(2)
	kolvo = k // n + 1
	f = k % n
	now = 0
	flag = True
	for i in range(n):
		ans = [0] * n
		if i >= f and flag:
			kolvo -= 1
			flag = False
		for j in range(kolvo):
			ans[now] = 1
			now += 1
			now %= n
		for j in ans:
			print(j, end='')
		print()


def solve(n, k):
	arr = [[0] * n for _ in range(n)]
	for i in range(k):
		arr[(i + i // n) % n][i % n] = 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(map(str, arr[i])))
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	solve(n, k)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0 for i in range(n)] for j in range(n)]
	(p, q) = (0, 0)
	for i in range(k):
		a[p][q] = 1
		p = p + 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	print(0 if k % n == 0 else 2)
	for sl in a:
		print(*sl, sep='')


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	grid = []
	for i in range(n):
		grid.append(['0'] * n)
	cnt = 0
	while cnt != k:
		u = cnt % n
		v = (u + cnt // n) % n
		grid[u][v] = '1'
		cnt += 1
	nax = -1
	nim = int(10000000000.0)
	for i in range(n):
		nax = max(nax, grid[i].count('1'))
		nim = min(nim, grid[i].count('1'))
	ans1 = (nax - nim) ** 2
	nax = -1
	nim = int(10000000000.0)
	grid_t = [list(x) for x in zip(*grid)]
	for i in range(n):
		nax = max(nax, grid[i].count('1'))
		nim = min(nim, grid[i].count('1'))
	ans2 = (nax - nim) ** 2
	print(ans1 + ans2)
	for i in range(n):
		print(''.join(grid[i]))


num = int(input())
for _ in range(num):
	(a, b) = map(int, input().split())
	arr = [[0 for i in range(a)] for j in range(a)]
	ans = 0
	i = 0
	j = 0
	ev = 2
	w = a - 1
	while i < a:
		while i < a and j < a:
			if ans == b:
				break
			else:
				arr[i][j] = 1
				ans += 1
			i += 1
			j += 1
		if ans == b:
			break
		if i == a and j == a:
			i = 1
			j = 0
		elif i == a and j != a:
			i = 0
			j = w
			w -= 1
		elif i != a and j == a:
			i = ev
			j = 0
			ev += 1
	s = a // 2
	s -= 1
	q = a // 2
	mx = 0
	mn = a
	for i in range(a):
		p = arr[i].count(1)
		if p > mx:
			mx = p
		if p < mn:
			mn = p
	wt = 0
	rt = 0
	xc = 0
	mw = 0
	for i in range(a):
		if arr[i][s] == 1:
			rt += 1
		if arr[i][q] == 1:
			xc += 1
		if arr[i][a - 1] == 1:
			wt += 1
		if arr[i][0] == 1:
			mw += 1
	ret = max(rt, xc, wt, mw)
	wt = min(wt, mw)
	wt = wt - ret
	mn = mn - mx
	wt = wt * wt
	mn *= mn
	print(wt + mn)
	for i in range(a):
		for j in range(a):
			print(arr[i][j], end='')
		print()


def print_mat():
	for i in mat:
		print(*i, sep='')
for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	mat = [[0] * n for i in range(n)]
	count = 0
	boo = False
	t = 0
	if k == 0:
		print(0)
		print_mat()
		continue
	for i in range(n):
		for j in range(n):
			if j + t >= n:
				mat[j + t - n][j] = 1
			else:
				mat[j + t][j] = 1
			count += 1
			if count == k:
				boo = True
				ans = t
				break
		if boo:
			break
		t += 1
	rmax = 0
	rmin = float('inf')
	cmax = 0
	cmin = float('inf')
	for i in range(n):
		a = sum(mat[i])
		b = sum([mat[j][i] for j in range(n)])
		if a > rmax:
			rmax = a
		if a < rmin:
			rmin = a
		if b > cmax:
			cmax = b
		if b < cmin:
			cmin = b
	print((rmax - rmin) ** 2 + (cmax - cmin) ** 2)
	print_mat()


t = int(input())
resultat = []
mat_tot = []
n_tot = []
for kk in range(t):
	(n, k) = map(str, input().split())
	n = int(n)
	k = int(k)
	n_tot.append(n)
	if k % n == 0:
		resultat.append(0)
	else:
		resultat.append(2)
	compt = 0
	num = int(k / n) + 1
	mat = [[0 for x in range(n)] for y in range(n)]
	i = 0
	j = 0
	while compt < k:
		if compt % n == 0:
			i = 0
			j = int(compt / n)
		elif i < n - 1 and j < n - 1:
			i += 1
			j += 1
		elif i == n - 1 and j < n - 1:
			i = 0
			j += 1
		elif i < n - 1 and j == n - 1:
			j = 0
			i += 1
		if mat[i][j] == 0:
			mat[i][j] = 1
			compt += 1
	for i in range(n):
		mat_tot.append(''.join(map(str, mat[i])))
anteriors = 0
for i in range(t):
	print(resultat[i])
	for j in range(n_tot[i]):
		print(''.join(map(str, mat_tot[j + anteriors])))
	anteriors += n_tot[i]


from sys import stdin, stdout

def main():
	t = int(stdin.readline())
	for case in range(t):
		(n, k) = map(int, stdin.readline().split())
		mtrx = [['0' for i in range(n)] for j in range(n)]
		if k == 0:
			ans = '0'
		else:
			if k % n == 0:
				ans = '0'
			else:
				ans = '2'
			(i, j) = (0, 0)
			while k > 0:
				mtrx[i % n][(i + j) % n] = '1'
				i = i + 1
				k = k - 1
				if i == n:
					i = 0
					j = j + 1
		stdout.write(ans)
		stdout.write('\n')
		for i in range(n):
			stdout.write(''.join(mtrx[i]))
			stdout.write('\n')
	return
main()


T = int(input())
for _ in range(T):
	(N, K) = map(int, input().split())
	ans = [[0] * N for _ in range(N)]
	for k in range(K):
		(d, i) = divmod(k, N)
		j = (i + d) % N
		ans[i][j] = 1
	(mnr, mxr) = (N, 0)
	for row in ans:
		s = sum(row)
		mnr = min(mnr, s)
		mxr = max(mxr, s)
	(mnc, mxc) = (N, 0)
	for col in zip(*ans):
		s = sum(col)
		mnc = min(mnc, s)
		mxc = max(mxc, s)
	v = (mxr - mnr) ** 2 + (mxc - mnc) ** 2
	print(v)
	for row in ans:
		print(''.join(map(str, row)))


for _ in range(0, int(input())):
	(n, k) = map(int, input().strip().split())
	res = 2
	if k % n == 0:
		res = 0
	m = [[0 for a in range(0, n)] for b in range(0, n)]
	offset = 1
	x = 0
	y = 0
	counter = 0
	while counter < k:
		m[x][y] = 1
		x = (x + 1) % n
		y = (y + 1) % n
		if counter % n == n - 1:
			x = 0
			y = offset
			offset += 1
		counter += 1
	print(res)
	for i in m:
		print(''.join((str(x) for x in i)))


import time, math, bisect, sys, heapq
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x))

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 9 + 7

def solve():
	(n, k) = IP()
	if k == 0:
		print(0)
		for i in range(n):
			print('0' * n)
	else:
		li = [['0' for j in range(n)] for i in range(n)]
		if k <= n:
			for i in range(k):
				li[i][i] = '1'
			if k == n:
				print(0)
			else:
				print(2)
			for ele in li:
				print(''.join(ele))
		else:
			for i in range(n):
				li[i][i] = '1'
			k -= n
			i = 1
			j = n - 1
			turn = 1
			while k > 0:
				if turn % 2 != 0:
					(x, y) = (i, 0)
					while k > 0 and x < n and (y < n):
						li[x][y] = '1'
						k -= 1
						x += 1
						y += 1
					i += 1
				else:
					(x, y) = (0, j)
					while k > 0 and x < n and (y < n):
						li[x][y] = '1'
						k -= 1
						x += 1
						y += 1
					j -= 1
				turn += 1
			(mxr, mnr, mxc, mnc) = (-1 * sys.maxsize, sys.maxsize, -1 * sys.maxsize, sys.maxsize)
			for ele in li:
				c = ele.count('1')
				mxr = max(mxr, c)
				mnr = min(mnr, c)
			for i in range(n):
				c = 0
				for j in range(n):
					if li[j][i] == '1':
						c += 1
				mxc = max(mxc, c)
				mnc = min(mnc, c)
			print((mxr - mnr) ** 2 + (mxc - mnc) ** 2)
			for ele in li:
				print(''.join(ele))
t = II()
for i in range(t):
	solve()


def solve(n, k):
	matrix = [[0 for _ in range(n)] for _ in range(n)]
	for right_move in range(n):
		for height in range(n):
			if k == 0:
				continue
			i = height
			j = (height + right_move) % n
			matrix[i][j] = 1
			k -= 1
	return matrix

def get_value(matrix):
	n = len(matrix)
	max_r = 0
	min_r = n
	max_c = 0
	min_c = n
	for line in matrix:
		value = sum(line)
		max_r = max(max_r, value)
		min_r = min(min_r, value)
	for j in range(n):
		value = sum([matrix[i][j] for i in range(n)])
		max_c = max(max_c, value)
		min_c = min(min_c, value)
	res = (max_r - min_r) ** 2
	res += (max_c - min_c) ** 2
	return res
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	matrix = solve(n, k)
	value = get_value(matrix)
	print(value)
	for line in matrix:
		print(''.join(map(str, line)))


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	a = [[0] * n for i in range(n)]
	cnt = 0
	if k % n == 0:
		print(0)
	else:
		print(2)
	(p, q) = (0, 0)
	for i in range(k):
		a[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = [[0] * n for i in range(n)]
	f = False
	for j in range(n):
		for i in range(n):
			if k == 0:
				f = True
				break
			k -= 1
			ans[i][(i + j) % n] = 1
		if f:
			break
	r = [sum(ans[i]) for i in range(n)]
	(mar, mir) = (max(r), min(r))
	c = [sum([ans[i][j] for i in range(n)]) for j in range(n)]
	(mac, mic) = (max(c), min(c))
	print((mar - mir) ** 2 + (mac - mic) ** 2)
	for i in range(n):
		print(''.join(map(str, ans[i])))


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0 for j in range(n)] for i in range(n)]
	x = 0
	ans = 0
	while k:
		(i, j) = (0, x)
		while k and i < n:
			a[i][j] = 1
			(i, j) = (i + 1, (j + 1) % n)
			k -= 1
		if i == n:
			ans = 0
		else:
			ans = 2
		x += 1
	print(ans)
	for i in a:
		print(''.join((str(j) for j in i)))


def tc():
	(n, k) = map(int, input().split())
	grid = [[0] * n for _ in range(n)]
	cnt = 0
	(r, c) = (0, 0)
	done = False if k else True
	offset = 0
	while not done:
		for _ in range(n):
			grid[r][c] = 1
			r = (r + 1) % n
			c = (c + 1) % n
			cnt += 1
			if cnt == k:
				done = True
				break
		c += 1
	rmin = n
	rmax = 0
	for r in grid:
		s = sum(r)
		rmin = min(s, rmin)
		rmax = max(s, rmax)
	cmin = n
	cmax = 0
	for c in zip(*grid):
		s = sum(c)
		cmin = min(s, cmin)
		cmax = max(s, cmax)
	print((rmax - rmin) ** 2 + (cmax - cmin) ** 2)
	for r in grid:
		print(''.join(map(str, r)))
T = int(input())
for _ in range(T):
	tc()


import sys
input = sys.stdin.readline
inputr = lambda : sys.stdin.readline().rstrip('\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	e = k // n
	T = [[0] * n for _ in range(n)]
	for i in range((k + n - 1) // n):
		for j in range(min(n, k - i * n)):
			T[j][(i + j) % n] = 1
	rows = [sum(R) for R in T]
	cols = [sum(C) for C in zip(*T)]
	assert sum(rows) == k
	assert sum(cols) == k
	print((max(rows) - min(rows)) ** 2 + (max(cols) - min(cols)) ** 2)
	for R in T:
		print(''.join(map(str, R)))


def rot_r(xs, k):
	return xs[-k:] + xs[:-k]

def solve(n, k):
	f = 0
	if k % n > 0:
		f = 2
	print(f)
	m = k // n
	r = k % n
	for rInd in range(n):
		row = [1] * m + [0] * (n - m)
		if rInd < r:
			row[m] = 1
		row = rot_r(row, rInd)
		print(''.join(map(str, row)))
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	solve(n, k)


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def gi():
	return [x for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)

def bo(i):
	return ord(i) - ord('a')
t = fi()
while t > 0:
	t -= 1
	(n, k) = mi()
	a = [['0' for i in range(n)] for j in range(n)]
	i = j = 0
	d = [i for i in range(n)]
	while k != 0:
		a[i][d[i]] = '1'
		j = d[i] + 1
		j %= n
		d[i] = j
		i += 1
		i %= n
		k -= 1
	c = [0 for i in range(n)]
	r = [0 for i in range(n)]
	for i in range(n):
		for j in range(n):
			c[j] += int(a[i][j])
			r[i] += int(a[i][j])
	z1 = max(c) - min(c)
	z2 = max(r) - min(r)
	print(z1 ** 2 + z2 ** 2)
	for i in a:
		print(''.join(i))


def co1(n, numd):
	lis = []
	for i in range(n):
		co = 0
		for j in range(n):
			if numd[i][j] == 1:
				co += 1
		lis.append(co)
	mar = max(lis)
	mir = min(lis)
	return (mar, mir)

def co2(n, numd):
	sto = []
	for i in range(n):
		co = 0
		for j in range(n):
			if numd[j][i] == 1:
				co += 1
		sto.append(co)
	mac = max(sto)
	mic = min(sto)
	return (mac, mic)

def ca(n, k):
	numd = [[0 for k in range(n)] for l in range(n)]
	p1 = k // n
	re = k % n
	ad = 1
	i1 = 0
	for i in range(n):
		if i1 >= n:
			i1 = 0
		st = i1
		if ad <= re:
			tp = p1 + 1
		else:
			tp = p1
		while tp > 0:
			if st >= n:
				st = 0
			numd[i][st] = 1
			st += 1
			tp -= 1
		i1 += 1
		ad += 1
	(mar, mir) = co1(n, numd)
	(mac, mic) = co2(n, numd)
	print((mar - mir) ** 2 + (mac - mic) ** 2)
	for i in range(n):
		for j in range(n):
			print(numd[i][j], end='')
		print()
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ca(n, k)


def solve(n, k):
	p = 0
	q = 0
	mat = []
	for i in range(n):
		mat.append([0 for j in range(n)])
	for i in range(k):
		mat[p][q] = 1
		p = p + 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	return mat
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	s = solve(n, k)
	print(0) if k % n == 0 else print(2)
	for it in s:
		print(*it, sep='')


def help():
	(n, k) = map(int, input().split(' '))
	toret = [[0] * n for i in range(n)]
	if k == 0 or k % n == 0:
		print(0)
	elif k != 0:
		print(2)
	for i in range(min(n, k)):
		toret[i][i] = 1
	k -= min(n, k)
	row_turn = 0
	j = 1
	while k > 0:
		if row_turn == 0:
			for i in range(min(n - j, k)):
				toret[i][i + j] = 1
			k -= min(n - j, k)
			for i in range(min(j, k)):
				toret[n - j + i][i] = 1
			k -= min(j, k)
			row_turn = 1
		else:
			for i in range(min(n - j, k)):
				toret[i + j][i] = 1
			k -= min(n - j, k)
			for i in range(min(j, k)):
				toret[i][n - j + i] = 1
			k -= min(j, k)
			row_turn = 0
			j += 1
	for i in range(n):
		print(*toret[i], sep='')
for _ in range(int(input())):
	help()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import math
testcases = int(input())
for j in range(testcases):
	(n, k) = map(int, input().split())
	init = k
	outy = {}
	for s in range(n):
		outy[s] = ['0'] * n
	cv = 0
	while init > 0:
		for s in range(min(init, n)):
			outy[s][(cv + s) % n] = '1'
			init -= 1
		cv += 1
	maxrow = 0
	minrow = n
	maxcol = 0
	mincol = n
	for s in range(n):
		rval = 0
		for b in range(n):
			if outy[s][b] == '1':
				rval += 1
		if rval > maxrow:
			maxrow = rval
		if rval < minrow:
			minrow = rval
	for s in range(n):
		cval = 0
		for b in range(n):
			if outy[b][s] == '1':
				cval += 1
		if cval > maxcol:
			maxcol = cval
		if cval < mincol:
			mincol = cval
	print((maxrow - minrow) ** 2 + (maxcol - mincol) ** 2)
	for s in range(n):
		print(''.join(outy[s]))


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	grid = [[0] * n for i in range(n)]
	cnt = 0
	i = 0
	j = 0
	while cnt < k:
		if grid[i][j]:
			i += 1
		grid[i][j] = 1
		i += 1
		if i == n:
			i = 0
		j += 1
		if j == n:
			j = 0
		cnt += 1
	(max1, max2) = (0, 0)
	(min1, min2) = (float('inf'), float('inf'))
	for i in range(n):
		sum1 = 0
		sum2 = 0
		for j in range(n):
			sum1 += grid[i][j]
			sum2 += grid[j][i]
		max1 = max(max1, sum1)
		min1 = min(min1, sum1)
		max2 = max(max2, sum2)
		min2 = min(min2, sum2)
	print((max1 - min1) ** 2 + (max2 - min2) ** 2)
	for row in grid:
		print(*row, sep='')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = [['0' for j in range(n)] for i in range(n)]
	posx = 0
	posy = 0
	count = k
	while count:
		ans[posx][posy] = '1'
		count -= 1
		if (k - count) % n != 0:
			posx = (posx + 1) % n
			posy = (posy + 1) % n
		else:
			posx = (posx + 1) % n
			posy = (posy + 2) % n
	res = 0
	R = [sum((int(ans[i][j]) for j in range(n))) for i in range(n)]
	C = [sum((int(ans[i][j]) for i in range(n))) for j in range(n)]
	res = (max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2
	print(res)
	for i in range(n):
		print(''.join(ans[i]))


import sys, math, cmath, time
start_time = time.time()

def qwqw(a, b):
	for i in range(len(a)):
		for j in range(len(a)):
			b[i][j] = a[j][i]
	return b

def solve():
	(n, k) = invr()
	q = [['0'] * n for i in range(n)]
	w = 0
	for i in range(len(q)):
		if i < k - k // n * n:
			for j in range(k // n + 1):
				q[i][w] = '1'
				w = (w + 1) % n
		else:
			for j in range(k // n):
				q[i][w] = '1'
				w = (w + 1) % n
	r = []
	c = []
	for i in range(len(q)):
		r.append(q[i].count('1'))
	ww = qwqw(q, [['0'] * n for i in range(n)])
	for i in range(len(ww)):
		c.append(ww[i].count('1'))
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in range(len(q)):
		print(''.join(q[i]))

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = (q[ord(a[i]) - 97], 1)
	return q

def factors(n):
	q = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			q.append(i)
			q.append(n // i)
	return list(sorted(list(set(q))))

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k == 0:
		print(0)
		kk = [0 for i in range(n)]
		for i in range(n):
			print(''.join(list(map(str, kk))))
	elif k % n == 0:
		print(0)
		b = k // n
		kk = [[0 for i in range(n)] for j in range(n)]
		i = 0
		summ = 0
		while i < b:
			for j in range(n):
				if i + j >= n:
					t = (i + j) % n
				else:
					t = i + j
				kk[j][t] = 1
				summ += 1
				if summ == k:
					break
					break
			i += 1
		for i in range(n):
			print(''.join(list(map(str, kk[i]))))
	else:
		print(2)
		b = k // n
		kk = [[0 for i in range(n)] for j in range(n)]
		i = 0
		summ = 0
		while i < b + 1:
			for j in range(n):
				if i + j >= n:
					t = (i + j) % n
				else:
					t = i + j
				kk[j][t] = 1
				summ += 1
				if summ == k:
					break
					break
			i += 1
		for i in range(n):
			print(''.join(list(map(str, kk[i]))))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k == n ** 2:
		print(0)
		ans = [[1] * n for i in range(n)]
		for i in range(n):
			for j in range(n):
				print(ans[i][j], end='')
			print()
		continue
	ans = [[0] * n for i in range(n)]
	cnt = 0
	flag = False
	for i in range(n):
		for j in range(n):
			if cnt == k:
				flag = True
				break
			cnt += 1
			ans[j][(j + i) % n] = 1
		if flag:
			break
	if k % n != 0:
		print(2)
	else:
		print(0)
	for i in range(n):
		for j in range(n):
			print(ans[i][j], end='')
		print()


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		(N, K) = [int(x) for x in input().split()]
		ans = [[0] * N for j in range(N)]
		cnt = 0
		f = False
		if K == 0:
			f = True
		for i in range(N):
			if f:
				break
			for j in range(N):
				ans[j % N][(i + j) % N] = 1
				cnt += 1
				if cnt == K:
					f = True
					break
			if f:
				break
		maxr = 0
		minr = float('inf')
		maxc = 0
		minc = float('inf')
		for a in ans:
			s = sum(a)
			maxr = max(maxr, s)
			minr = min(minr, s)
		for a in zip(*ans):
			s = sum(a)
			maxc = max(maxc, s)
			minc = min(minc, s)
		print((maxr - minr) ** 2 + (maxc - minc) ** 2)
		for a in ans:
			print(''.join(map(str, a)))
main()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
		d = k // n
		r = '1' * d + '0' * (n - d)
		print(r)
		for i in range(1, n):
			print(r[i:] + r[:i])
	else:
		print(2)
		d = k // n
		d1 = k % n
		eye = [[0] * n for _ in range(n)]
		for j in range(d):
			for i in range(n):
				eye[i][(i + j) % n] = 1
		for i in range(d1):
			eye[i][(i + d) % n] = 1
		for r in eye:
			print(''.join(map(str, r)))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	ans = [[0] * n for i in range(n)]
	cnt = 0
	for i in range(n):
		for j in range(n):
			if cnt == k:
				break
			ans[j][(i + j) % n] = 1
			cnt += 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for res in ans:
		print(''.join(map(str, res)))


for w in range(int(input())):
	(n, k) = map(int, input().strip().split())
	flag = False
	A = [[0] * n for i in range(n)]
	j = 0
	while j < k:
		a = j // n
		for i in range(n):
			if j >= k:
				flag = True
				break
			A[i][(i + a) % n] = 1
			j += 1
		if flag:
			break
	p = [2, 0]
	print(p[k % n == 0])
	for i in range(n):
		s = ''
		for j in A[i]:
			s += str(j)
		print(s)


from itertools import combinations
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = [['0'] * n for _ in range(n)]
	i = j = si = 0
	while k:
		if ans[i][j] == '1':
			si += 1
			i = si
			j = 0
		else:
			ans[i][j] = '1'
			i = (i + 1) % n
			j = (j + 1) % n
			k -= 1
	row = [i.count('1') for i in ans]
	col = [i.count('1') for i in [*zip(*ans)]]
	fa = (max(row) - min(row)) ** 2 + (max(col) - min(col)) ** 2
	print(fa)
	for i in ans:
		print(''.join(i))


import sys
from sys import stdin
from collections import deque, Counter
from math import factorial
from itertools import groupby

def neo():
	return map(int, input().split())

def Neo():
	return list(map(int, input().split()))
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = []
	for i in range(n):
		ans.append([0] * n)
	for i in range(k):
		ans[(i + i // n) % n][i % n] += 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join([str(x) for x in ans[i]]))


try:
	k = int(input())
	for i in range(k):
		n = list(map(int, input().split()))
		if n[1] % n[0] == 0:
			print(0)
		else:
			print(2)
		reach = n[1] // n[0]
		rthr = n[1] % n[0]
		coi = 0
		mat = [[0 for x in range(n[0])] for y in range(n[0])]
		for r in range(len(mat)):
			if r + reach <= len(mat):
				for e in range(r, r + reach):
					mat[r][e] = 1
				coi += reach
				if r < rthr:
					if r + reach == len(mat):
						mat[r][0] = 1
					else:
						mat[r][r + reach] = 1
			else:
				for e in range(r, len(mat)):
					mat[r][e] = 1
				for e in range(0, reach - (len(mat) - r)):
					mat[r][e] = 1
				coi += reach
				if r < rthr:
					mat[r][reach - (len(mat) - r)] = 1
			string = ''
			for e in range(len(mat)):
				string += str(mat[r][e])
			print(string)
except Exception:
	pass


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k == 0:
		print(0)
		print('\n'.join(['0' * n for _ in range(n)]))
	else:
		(q, r) = divmod(k, n)
		print(0 if r == 0 else 2)
		for i in range(n):
			row = ['1'] * q + ['0'] * (n - q)
			if i < r:
				row[q] = '1'
			print(''.join(row[-i:] + row[:-i]))


for i in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	a = [[0] * n for i in range(n)]
	x = 0
	y = 0
	f = [i for i in range(n)]
	while True:
		if k > 0:
			a[x][f[y]] = 1
		else:
			break
		if f[y] == n - 1:
			f[y] = 0
		else:
			f[y] += 1
		if y == n - 1:
			y = 0
		else:
			y += 1
		if x == n - 1:
			x = 0
		else:
			x += 1
		k -= 1
	for l in a:
		print(''.join((str(t) for t in l)))


t = int(input(''))

def compute_f(a, n):
	row_sums = [sum(row) for row in a]
	column_sums = [sum((a[j][i] for i in range(n))) for j in range(n)]
	max_r = max(row_sums)
	min_r = min(row_sums)
	max_c = max(column_sums)
	min_c = min(column_sums)
	return (max_r - min_r) ** 2 + (max_c - min_c) ** 2

def print_a(a):
	for row in a:
		out = ''
		for num in row:
			out += str(num)
		print(out)

def solve(n, k):
	assert k <= n * n
	A = [[0 for i in range(n)] for j in range(n)]
	for x in range(k):
		j = x // n
		i = x % n
		A[i][(i + j) % n] = 1
	print(compute_f(A, n))
	print_a(A)
for i in range(t):
	[n, k] = [int(num) for num in input('').split(' ')]
	solve(n, k)


t = int(input())
for t in range(t):
	(n, k) = map(int, input().split())
	ans = [[0 for _ in range(n)] for _ in range(n)]
	r = [0 for _ in range(n)]
	c = [0 for _ in range(n)]
	ind = [(0, 0)]
	for i in range(1, n):
		ind.append((0, i))
		ind.append((n - i, 0))
	ind = iter(ind)
	while k > 0:
		(i, j) = next(ind)
		while i < n and j < n and (k > 0):
			ans[i][j] = 1
			c[j] += 1
			r[i] += 1
			i += 1
			j += 1
			k -= 1
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in range(n):
		for j in range(n):
			print(ans[i][j], end='')
		print()


for x in range(int(input())):
	(n, k) = list(map(int, input().split()))
	m = a = [[1] * n for i in range(n)]
	k = n * n - k
	for i in range(n):
		for j in range(n):
			if k > 0:
				if m[j % n][(i + j) % n] == 1:
					m[j % n][(i + j) % n] = 0
					k -= 1
	r = []
	c = []
	for i in range(n):
		r.append(sum(m[i]))
	r.sort()
	for i in range(n):
		s = 0
		for j in range(n):
			s += m[j][i]
		c.append(s)
	c.sort()
	print((r[0] - r[-1]) ** 2 + (c[0] - c[-1]) ** 2)
	for i in range(n):
		print(''.join((str(j) for j in m[i][::1])))


T = int(input())
for t in range(T):
	(n, k) = (int(i) for i in input().split())
	a = [[0 for j in range(n)] for i in range(n)]
	(i, j) = (0, 0)
	if k > 0:
		a[i][j] = 1
	for l in range(k - 1):
		j += 1
		if j == n:
			j = 0
			i += 1
		if i == n:
			i = 0
		i += 1
		if i == n:
			i = 0
		a[i][j] = 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


import collections as cc
import math as mt
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n, k) = I()
	ans = [[0] * n for i in range(n)]
	temp = []
	r = [0 for i in range(n)]
	c = [0 for i in range(n)]
	f = cc.defaultdict(list)
	for i in range(n):
		for j in range(n):
			f[i - j].append([i, j])
	an = [i for i in range(n)]
	for i in an:
		for j in f[-i]:
			if not k:
				break
			(x, y) = j
			r[x] += 1
			c[y] += 1
			ans[x][y] = 1
			k -= 1
		if i != 0:
			for j in f[n - i]:
				if not k:
					break
				(x, y) = j
				r[x] += 1
				c[y] += 1
				ans[x][y] = 1
				k -= 1
			if not k:
				break
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in ans:
		for j in i:
			print(j, end='')
		print()


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		(n, k) = list(map(int, input().split()))
		perit = k // n
		rem = k % n
		ans = 0
		if rem:
			ans = 2
		anslst = []
		for i in range(n):
			if i < rem:
				tempans = '1' * max(perit + 1 + i - n, 0) + '0' * (i - max(perit + 1 + i - n, 0)) + '1' * (perit + 1 - max(perit + 1 + i - n, 0)) + '0' * (n - perit - i - 1)
			else:
				tempans = '1' * max(perit + i - n, 0) + '0' * (i - max(perit + i - n, 0)) + '1' * (perit - max(perit + i - n, 0)) + '0' * (n - perit - i)
			anslst.append(tempans)
		yield ans
		for i in range(n):
			yield anslst[i]
t = int(input())
ans = gift()
print(*ans, sep='\n')


def answer(n, k):
	copy = k
	dp = [[0 for i in range(n)] for j in range(n)]
	for i in range(n):
		for j in range(n):
			row = j
			col = (i + j) % n
			if k > 0:
				dp[row][col] = 1
				k -= 1
			else:
				break
	l = []
	for i in range(n):
		s = ''
		for j in range(n):
			s += str(dp[i][j])
		l.append(s)
	if copy == 0 or copy == n * n:
		return (0, l)
	if copy >= n:
		if copy % n == 0:
			return (0, l)
		else:
			return (2, l)
	if copy < n:
		return (2, l)
t = int(input())
for x in range(t):
	(n, k) = map(int, input().split())
	(a, b) = answer(n, k)
	print(a)
	for i in b:
		print(i)


def solve(n, k):
	matrix = [['1'] * n for _ in range(n)]
	R = [n for i in range(n)]
	C = [n for i in range(n)]
	(cur_x, cur_y) = (0, n - 1)
	i = 0
	while i < n * n - k:
		if matrix[cur_x][cur_y] == '0':
			cur_y = (cur_y + 1) % n
		else:
			matrix[cur_x][cur_y] = '0'
			R[cur_x] -= 1
			C[cur_y] -= 1
			cur_x = (cur_x - 1) % n
			cur_y = (cur_y + 1) % n
			i += 1
	f = (max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2
	print(f)
	for r in matrix:
		print(''.join(r))
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	solve(n, k)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	out = []
	for i in range(n):
		out.append([0] * n)
	p = 0
	q = 0
	while k > 0:
		k -= 1
		out[p][q] = 1
		p += 1
		q += 1
		q %= n
		if p == n:
			p = 0
			q += 1
			q %= n
	for i in range(n):
		for j in range(n):
			print(out[i][j], end='')
		print()


import os
import operator
from collections import defaultdict
import sys
from io import BytesIO, IOBase
import bisect

def inar():
	return [int(el) for el in input().split()]

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		matrix = []
		for i in range(n):
			lis = ['0' for i in range(n)]
			matrix.append(lis)
		arr = [0] * n
		for i in range(n):
			if k > 0:
				matrix[i][i] = '1'
				arr[i] = i
				k -= 1
			else:
				break
		if k > 0:
			while k > 0:
				for i in range(n):
					if k > 0:
						matrix[i][(arr[i] + 1) % n] = '1'
						arr[i] = (arr[i] + 1) % n
						k -= 1
					else:
						break
		rmn = 10 ** 5
		rmx = 0
		for i in range(n):
			sm = 0
			for j in range(n):
				sm += int(matrix[i][j])
			rmx = max(rmx, sm)
			rmn = min(rmn, sm)
		cmn = 10 ** 5
		cmx = 0
		for i in range(n):
			sm = 0
			for j in range(n):
				sm += int(matrix[j][i])
			cmx = max(cmx, sm)
			cmn = min(cmn, sm)
		ans = (rmx - rmn) ** 2 + (cmx - cmn) ** 2
		print(ans)
		for i in range(n):
			print(''.join(matrix[i]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
import math
T = int(input())

def f(M):
	minR = math.inf
	maxR = -math.inf
	minC = math.inf
	maxC = -math.inf
	for i in range(len(M)):
		sumRow = sum(M[i])
		minR = min(minR, sumRow)
		maxR = max(maxR, sumRow)
		sumCol = sum([M[el][i] for el in range(len(M))])
		maxC = max(maxC, sumCol)
		minC = min(minC, sumCol)
	return (maxR - minR) ** 2 + (maxC - minC) ** 2
for t in range(T):
	(N, K) = [int(_) for _ in input().split()]
	M = [[0] * N for i in range(N)]
	for i in range(K):
		M[i % N][(i // N + i) % N] = 1
	print(f(M))
	for row in M:
		print(''.join(map(str, row)))


for s in [*open(0)][1:]:
	(n, k) = map(int, s.split())
	print(k % n and 2)
	for i in range(n):
		s = ((k + i) // n * '1').zfill(n)
		print(s[i:] + s[:i])


from sys import stdin
from collections import deque
mod = 10 ** 9 + 7
import sys
import random
from queue import PriorityQueue
from collections import Counter as cc
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdict
from math import sqrt, factorial, gcd, log2, inf, ceil
import heapq
input = lambda : sys.stdin.readline().rstrip()
from sys import stdin, stdout
from heapq import heapify, heappush, heappop
from itertools import permutations
from math import factorial as f

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
import sys
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	la = []
	for i in range(n):
		l = ['0'] * n
		la.append(l)
	count = 0
	(i, j) = (0, 0)
	(x, y) = (n, 0)
	while k != 0:
		la[i][j] = '1'
		k -= 1
		i += 1
		j += 1
		if i >= n or j >= n:
			if count % 2 == 0:
				y += 1
				i = 0
				j = y
			else:
				x -= 1
				j = 0
				i = x
			count += 1
	la1 = []
	la2 = []
	for i in range(n):
		cnt1 = 0
		for j in range(n):
			cnt1 += int(la[i][j])
		la1.append(cnt1)
		cnt1 = 0
		for j in range(n):
			cnt1 += int(la[j][i])
		la2.append(cnt1)
	ans = 0
	la1.sort()
	la2.sort()
	ans += (la1[0] - la1[-1]) ** 2 + (la2[0] - la2[-1]) ** 2
	print(ans)
	for i in la:
		print(''.join(i))


import math
from collections import deque
import sys
sys.setrecursionlimit(10 ** 4)

def Divisors(n):
	l = []
	i = 2
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
		i = i + 1
	return l

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(n)
	return l

def Factors(n):
	result = []
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			if i == n / i:
				result.append(i)
			else:
				result.append(i)
				result.append(n // i)
	result.append(1)
	result.append(n)
	return result

def maxSubArraySum(a):
	max_so_far = 0
	max_ending_here = 0
	size = len(a)
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < abs(max_ending_here):
			max_so_far = max_ending_here
	return max_so_far

def longestsubarray(arr, n, k):
	current_count = 0
	max_count = 0
	for i in range(0, n, 1):
		if arr[i] % k != 0:
			current_count += 1
		else:
			current_count = 0
		max_count = max(current_count, max_count)
	return max_count

def main():
	(n, k) = list(map(int, input().split()))
	p = k // n
	r = k % n
	l1 = []
	for i in range(0, n):
		l1.append(0)
	for i in range(0, p):
		l1[i] = 1
	if r != 0:
		l1[p] = 1
	l = []
	for i in range(0, r):
		l.append(l1)
		l1 = l1[n - 1:] + l1[:n - 1]
	l1 = []
	for i in range(0, n):
		l1.append(0)
	for i in range(0, p):
		l1[i] = 1
	for i in range(0, r):
		l1 = l1[n - 1:] + l1[:n - 1]
	for i in range(r, n):
		l.append(l1)
		l1 = l1[n - 1:] + l1[:n - 1]
	r1 = 0
	c1 = 0
	r2 = n
	c2 = n
	for i in range(0, n):
		s1 = 0
		s2 = 0
		for j in range(0, n):
			s1 += l[i][j]
			s2 += l[j][i]
		if s1 > r1:
			r1 = s1
		if s2 > c1:
			c1 = s2
		if s1 < r2:
			r2 = s1
		if s2 < c2:
			c2 = s2
	print((r1 - r2) ** 2 + (c1 - c2) ** 2)
	for i in range(0, n):
		s = ''
		for j in range(0, n):
			if l[i][j] == 1:
				s += '1'
			else:
				s += '0'
		print(s)
t = int(input())
for i in range(0, t):
	main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	temp = k // n
	d = k % n
	ans = []
	(kp, op) = (0, d)
	for i in range(n):
		ok = ['0' for z in range(n)]
		for m in range(temp + 1):
			if op == 0 and m == temp:
				continue
			ok[kp % n] = '1'
			kp += 1
			if m == temp:
				op -= 1
		ans.append(ok)
	if d == 0:
		print(0)
	else:
		print(2)
	for i in ans:
		print(''.join(i))


for t in range(int(input())):
	(n, k) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(str(i))
	arr = []
	arr.append(a)
	for i in range(1, n):
		temp = a[i:] + a[:i]
		arr.append(list(temp))
	ans = []
	for i in range(n):
		ans.append(['0'] * n)
	index = 0
	index1 = 0
	indexes = []
	for i in range(k):
		indexes.append(index)
		indexes.append(int(arr[index1][index]))
		index += 1
		if index == n:
			index = 0
			index1 += 1
	for i in range(1, len(indexes), 2):
		ans[indexes[i - 1]][indexes[i]] = '1'
	if k < n:
		if k == 0:
			print(0)
		else:
			print(2)
	elif k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(ans[i]))


def solve():
	(n, k) = map(int, input().split())
	if k == 0:
		print(0)
		for _ in range(n):
			print('0' * n)
		return
	rows = [n] * n
	ans = [['1'] * n for _ in range(n)]
	i = 0
	j = 0
	if k % n == 0:
		count = 0
	else:
		count = 2
	big = n - k % n
	x = k // n
	p = n ** 2
	c = n - x
	while p > k:
		if not (j < big and rows[j] == x or (j >= big and rows[j] == x + 1)):
			p -= 1
			rows[j] -= 1
			ans[j][i] = '0'
			c -= 1
			if c == 0:
				i += 1
				if i >= big:
					c = n - (x + 1)
				else:
					c = n - x
		j = (j + 1) % n
	print(count)
	for s in ans:
		print(''.join(s))
t = int(input())
for _ in range(t):
	solve()


from sys import stdin
from heapq import *

class Node:

	def __init__(self, col):
		self.col = col
		self.val = 0

	def __lt__(self, other):
		return self.val < other.val
for _ in range(int(stdin.readline())):
	(n, k) = map(int, stdin.readline().split())
	cols = [Node(i) for i in range(n)]
	heapify(cols)
	arr = [['0'] * n for _ in range(n)]
	x = k % n
	for i in range(n):
		tak = []
		for _ in range(k // n + (x > 0)):
			tak.append(heappop(cols))
		for xx in tak:
			xx.val += 1
			heappush(cols, xx)
		x -= 1
		for j in tak:
			arr[i][j.col] = '1'
	if k % n:
		print(2)
	else:
		print(0)
	for i in arr:
		print(''.join(i))


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import sys

def solve(n, k):
	(p, q) = (k // n, k % n)
	Ans = [[0] * n for _ in range(n)]
	for i in range(p):
		for x in range(n):
			y = (x + i) % n
			Ans[x][y] = 1
	for x in range(q):
		y = (x + p) % n
		Ans[x][y] = 1
	cnt = int(q != 0) * 2
	return (cnt, Ans)

def main():
	mod = 1000000007
	inv = lambda x: pow(x, mod - 2, mod)
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		(cnt, Ans) = solve(n, k)
		sys.stdout.write(str(cnt) + '\n')
		for ans in Ans:
			sys.stdout.write(''.join(map(str, ans)) + '\n')
main()


for p in range(int(input())):
	(n, k) = input().split()
	n = int(n)
	k = int(k)
	ans = []
	for i in range(n):
		ans.append([0] * n)
	for i in range(n):
		if k > 0:
			ans[i][i] = 1
			k -= 1
	for i in range(n - 1, 0, -1):
		for l in range(0, i):
			if k > 0:
				f = n - i
				ans[l + f][l] = 1
				k -= 1
		for j in range(0, n - i):
			if k > 0:
				ans[j][j + i] = 1
				k -= 1
	r = []
	c = []
	for d in ans:
		r.append(sum(d))
	for i in range(n):
		s = 0
		for j in range(n):
			s += ans[j][i]
		c.append(s)
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for d in ans:
		d = list(map(str, d))
		print(''.join(d))


t = int(input())
while t:
	t -= 1
	(n, k) = input().split()
	n = int(n)
	k = int(k)
	a = [[0 for i in range(n)] for j in range(n)]
	p = 0
	if k == 0:
		print(0)
	else:
		val = k
		for i in range(n):
			if k <= 0:
				break
			a[i + p][i] = 1
			k -= 1
		while k > 0:
			p += 1
			for i in range(n - p):
				if k <= 0:
					break
				a[i + p][i] = 1
				k -= 1
			for i in range(p):
				if k <= 0:
					break
				a[i][n - p + i] = 1
				k -= 1
		if val % n:
			print(2)
		else:
			print(0)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def main():
	for _ in range(N()):
		(n, k) = RL()
		if k % n == 0:
			print(0)
		else:
			print(2)
		res = '1' * (k // n)
		num = k % n
		for i in range(n):
			now = res
			if num > 0:
				now += '1'
				num -= 1
			now += '0' * (n - len(now))
			print(now[i:] + now[:i])
main()


def solve(n, k):
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	grid = []
	for _ in range(n):
		grid.append([0] * n)
	curC = 0
	(r, c) = (0, 0)
	for _ in range(k):
		grid[r][c] = 1
		(r, c, curC) = nextRC(r, c, n, curC)
	return (ans, grid)

def nextRC(r, c, n, curC):
	nr = (r + 1) % n
	nc = (c + 1) % n
	if r == n - 1:
		curC += 1
		nc = curC
	return (nr, nc, curC)

def print_grid(grid):
	n = len(grid)
	for r in range(n):
		for c in range(n):
			print(grid[r][c], end='')
		print()
t = int(input())
for case in range(t):
	(n, k) = map(int, input().strip().split())
	(ans, grid) = solve(n, k)
	print(ans)
	print_grid(grid)


t = int(input())

def f(x):
	return x * (x + 1) // 2
for i in range(t):
	(n, k) = [int(x) for x in input().split()]
	answer = [['0' for j in range(n)] for i in range(n)]
	rsum = [0 for i in range(n)]
	csum = [0 for i in range(n)]
	for j in range(n):
		for i in range(n):
			if not k:
				break
			k -= 1
			col = (i + j) % n
			answer[i][col] = '1'
			rsum[i] += 1
			csum[col] += 1
	penalty = (max(rsum) - min(rsum)) ** 2 + (max(csum) - min(csum)) ** 2
	print(penalty)
	for line in answer:
		print(''.join(line))


production = True
import sys, math, collections

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()[:-1]
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = list(next_line)
		elif input_format == 4:
			formatted_input = list(map(int, list(next_line)))
		elif input_format == 5:
			formatted_input = next_line.split()
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 2:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$', end='')
		print(*args)
enu = enumerate
ter = lambda a, b, c: b if a else c

def mapl(iterable, format=0):
	if format == 0:
		return list(map(int, iterable))
	elif format == 1:
		return list(map(str, iterable))
	elif format == 2:
		return list(map(list, iterable))

def dg(s):
	return (s[0] + 1, s[1] + 1)

def pr(m):
	for i in m:
		log(i)
	log('')

def solve():
	(n, k) = input(1)
	m = [[0] * n for i in range(n)]
	t = 0
	for i in range(n):
		pr(m)
		if t >= k:
			break
		s1 = (i, 0)
		s2 = (0, n - i)
		for j in range(n - i):
			if t >= k:
				break
			m[s1[0]][s1[1]] = 1
			t += 1
			s1 = dg(s1)
		for j in range(i):
			if t >= k:
				break
			m[s2[0]][s2[1]] = 1
			t += 1
			s2 = dg(s2)
	pr(m)
	out(ter(k % n, 2, 0))
	for i in m:
		out(''.join(map(str, i)))
	return
for i in range(input(11)):
	solve()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = []
	for i in range(n):
		l.append([0] * n)
	if k % n == 0:
		print(0)
	else:
		print(2)
	i = 0
	while k > 0:
		x = i
		y = 0
		while k > 0 and y < n:
			l[y][x] = 1
			k -= 1
			x += 1
			y += 1
			if x == n:
				x = 0
		i += 1
	for i in range(n):
		for j in range(n):
			print(l[i][j], end='')
		print()


import sys
input = lambda : sys.stdin.readline().rstrip()
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print('0')
	else:
		print('2')
	for i in range(n):
		ans = ''
		if i < k % n:
			ans = '1' * (k // n + 1) + '0' * (n - (k // n + 1))
			ans = ans[i:] + ans[:i]
		else:
			ans = '1' * (k // n) + '0' * (n - k // n)
			ans = ans[i:] + ans[:i]
		print(ans)


t = int(input())
for z in range(t):
	(n, k) = map(int, input().split(' '))
	if k % n == 0:
		print(0)
	else:
		print(2)
	thing = k % n
	index = 0
	printlist = []
	while index < n:
		if thing > 0:
			thing -= 1
			if index + k // n + 1 > n:
				printlist.append((index + k // n - n + 1) * '1' + (n - k // n - 1) * '0' + (n - index) * '1')
			else:
				printlist.append(index * '0' + (k // n + 1) * '1' + (n - k // n - index - 1) * '0')
		elif index + k // n > n:
			printlist.append((index + k // n - n) * '1' + (n - k // n) * '0' + (n - index) * '1')
		else:
			printlist.append(index * '0' + k // n * '1' + (n - k // n - index) * '0')
		index += 1
	if len(printlist) == 0:
		print(0)
	for i in printlist:
		print(i)


import sys
readline = lambda : sys.stdin.readline().strip('\n')
readlist = lambda : list(map(int, readline().split()))
for i in range(int(input())):
	(n, k) = readlist()
	array = [['0'] * n for i in range(n)]
	print([0, 2][k % n > 0])
	(p, q) = (0, 0)
	for i in range(k):
		array[p][q] = '1'
		(p, q) = (p + 1, (q + 1) % n)
		if p == n:
			(p, q) = (0, (q + 1) % n)
	for i in range(n):
		print(''.join(array[i]))
quit()
for i in range(int(input())):
	(a, b, n, m) = readlist()
	if m > min(a, b) or a + b < n + m:
		print('No')
	else:
		print('Yes')
for i in range(int(input())):
	(n, r) = readlist()
	s = 0
	if n > r:
		print(r * (r + 1) // 2)
	else:
		print(n * (n - 1) // 2 + 1)
for i in range(int(input())):
	n = int(input())
	print(n // 2 + n % 2)
	a = 1


t = int(input())
for k in range(t):
	(n, k) = map(int, input().split())
	a = []
	for i in range(n):
		a.append([0] * n)
	if k <= n:
		for i in range(k):
			a[i][i] = 1
	else:
		for i in range(n):
			a[i][i] = 1
		k -= n
		i = 1
		j = 0
		nd = 1
		half = True
		for q in range(k):
			a[i][j] = 1
			i += 1
			j += 1
			if half:
				if i >= n:
					i = 0
					j = n - nd
					half = False
			elif j >= n:
				j = 0
				nd += 1
				i = nd
				half = True
	maxcount = 0
	mincount = n
	for i in range(n):
		s = 0
		for j in range(n):
			s += a[i][j]
		if s > maxcount:
			maxcount = s
		if s < mincount:
			mincount = s
	res = (maxcount - mincount) ** 2
	maxcount = 0
	mincount = n
	for j in range(n):
		s = 0
		for i in range(n):
			s += a[i][j]
		if s > maxcount:
			maxcount = s
		if s < mincount:
			mincount = s
	res += (maxcount - mincount) ** 2
	print(res)
	for i in range(n):
		print(''.join(map(str, a[i])))


for nt in range(int(input())):
	(n, k) = map(int, input().split())
	if k == n ** 2:
		print(0)
		ans = []
		for i in range(n):
			ans.append('1' * n)
		for i in ans:
			print(i)
		continue
	minn = k // n
	maxx = minn + 1
	cmaxx = k % n
	cminn = n - cmaxx
	count = 1
	ans = [[]]
	for i in range(n):
		if i < minn:
			ans[-1].append('1')
		else:
			ans[-1].append('0')
	cminn -= 1
	if cmaxx == 0:
		print(0)
	else:
		print(2)
	prev = ans[-1].index('0')
	while cminn or cmaxx:
		ans.append([0] * n)
		flag = 0
		if cminn > 0:
			nxt = 0
			for i in range(prev, prev + n):
				if i - prev < minn:
					ans[-1][i % n] = '1'
				else:
					if not flag:
						nxt = i % n
						flag = 1
					ans[-1][i % n] = '0'
			cminn -= 1
			prev = nxt
			continue
		if cmaxx > 0:
			nxt = 0
			for i in range(prev, prev + n):
				if i - prev < maxx:
					ans[-1][i % n] = '1'
				else:
					if not flag:
						nxt = i % n
						flag = 1
					ans[-1][i % n] = '0'
			cmaxx -= 1
			prev = nxt
	for i in ans:
		print(''.join(map(str, i)))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k == 0:
		x = 0
		p = [['0' for j in range(n)] for i in range(n)]
	elif n * n == k:
		x = 0
		p = [['1' for j in range(n)] for i in range(n)]
	elif n == k:
		x = 0
		p = [['1' if i == j else '0' for j in range(n)] for i in range(n)]
	elif n > k:
		x = 2
		p = [['1' if i == j and i < k else '0' for j in range(n)] for i in range(n)]
	else:
		if k % n == 0:
			x = 0
		else:
			x = 2
		p = [['0' for i in range(n)] for j in range(n)]
		a = k // n
		b = k % n
		c = 0
		for i in range(n):
			for j in range(n):
				if i == j:
					if c < b:
						for z in range(a + 1):
							p[i][(j + z) % n] = '1'
						c += 1
					else:
						for z in range(a):
							p[i][(j + z) % n] = '1'
	print(x)
	for i in range(n):
		print(''.join(p[i]))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	i = 0
	a = []
	for i in range(n):
		a += ([0] * n,)
	c = -1
	i = 0
	while i < k:
		if i % n == 0:
			c += 1
		a[i % n][c % n] = 1
		i += 1
		c += 1
	print(2 if k % n else 0)
	for x in a:
		print(*x, sep='')


for t in range(int(input())):
	(n, k) = map(int, input().split())
	print(0 if k % n == 0 else 2)
	a = [[0] * n for i in range(n)]
	(c, r) = (0, n - 1)
	while k > 0:
		(i, j) = (0, c)
		while k > 0 and j < n:
			a[i][j] = 1
			(i, j, k) = (i + 1, j + 1, k - 1)
		c = c + 1
		(i, j) = (r, 0)
		while k > 0 and i < n:
			a[i][j] = 1
			(i, j, k) = (i + 1, j + 1, k - 1)
		r -= 1
	for i in a:
		print(''.join((str(x) for x in i)))


from math import *
from heapq import heappush, heappop
from collections import *

def fastio():
	import sys
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip()
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = [['0'] * n for i in range(n)]
	(r, c) = (0, 0)
	for i in range(k):
		a[r][c] = '1'
		(r, c) = (r + 1, c + 1)
		if r == n:
			c += 1
			r = 0
		c %= n
	(maxR, maxC, minR, minC) = (0, 0, inf, inf)
	for i in range(n):
		row = [a[i][j] == '1' for j in range(n)]
		col = [a[j][i] == '1' for j in range(n)]
		maxR = max(maxR, sum(row))
		minR = min(minR, sum(row))
		maxC = max(maxC, sum(col))
		minC = min(minC, sum(col))
	print((maxR - minR) ** 2 + (maxC - minC) ** 2)
	for i in a:
		print(''.join(i))


from sys import stdin, gettrace
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def solve():
	(n, k) = map(int, inputi().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	aa = [['0'] * n for _ in range(n)]
	for i in range(k):
		aa[i % n][(i // n + i) % n] = '1'
	for a in aa:
		print(''.join(a))

def main():
	t = int(inputi())
	for _ in range(t):
		solve()
main()


import math
import bisect
import sys
from collections import OrderedDict
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
T = inp()
for t in range(T):
	(n, k) = invr()
	k1 = k
	out = [['0' for i in range(n)] for j in range(n)]
	rows = [n for i in range(n)]
	cols = [n for i in range(n)]
	up = False
	down = True
	uin = n - 1
	din = 0
	start = False
	while k1 != 0:
		if up:
			if not start:
				c = uin
				r = 0
				start = True
			out[r][c] = '1'
			rows[r] -= 1
			cols[c] -= 1
			r += 1
			c += 1
			if c == n:
				uin -= 1
				up = False
				down = True
				start = False
		else:
			if not start:
				c = 0
				r = din
				start = True
			out[r][c] = '1'
			rows[r] -= 1
			cols[c] -= 1
			r += 1
			c += 1
			if r == n:
				din += 1
				down = False
				up = True
				start = False
		k1 -= 1
	minnc = min(cols)
	maxxc = max(cols)
	minnr = min(rows)
	maxxr = max(rows)
	print((minnc - maxxc) ** 2 + (minnr - maxxr) ** 2)
	for ll in range(n):
		print(''.join(out[ll]))


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
		L = []
		c = 0
		d = k % n
		s = str()
		for i in range(n):
			if c < k // n:
				s = s + '1'
			else:
				s = s + '0'
			c = c + 1
		L = L + [s]
		for i in range(n - 1):
			y = L[i]
			b = y[n - 1]
			y = y[:n - 1]
			L = L + [b + y]
	else:
		print(2)
		L = []
		c = 0
		d = e = k % n - 1
		s = str()
		for i in range(n):
			if c < k // n + 1:
				s = s + '1'
			else:
				s = s + '0'
			c = c + 1
		L = L + [s]
		for i in range(d):
			y = L[i]
			b = y[n - 1]
			y = y[:n - 1]
			L = L + [b + y]
		z = L[e]
		z = z.replace('1', '0', 1)
		p = z[n - 1]
		z = z[:n - 1]
		L = L + [p + z]
		for i in range(e + 1, n - 1):
			y = L[i]
			b = y[n - 1]
			y = y[:n - 1]
			L = L + [b + y]
	for i in L:
		print(i)


import sys
T = int(sys.stdin.readline())
for _ in range(T):
	(n, k) = map(int, sys.stdin.readline().split())
	list_last = [i - 1 for i in range(n)]
	list_grid = [['0'] * n for i in range(n)]
	for y in range(k):
		list_last[y % n] = (list_last[y % n] + 1) % n
		list_grid[y % n][list_last[y % n]] = '1'
	print(2 if k % n else 0)
	[print(''.join(a)) for a in list_grid]


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0 for i in range(n)] for j in range(n)]
	(i, j) = (0, 0)
	if k % n == 0:
		fin = 0
	else:
		fin = 2
	for o in range(k):
		mat[i][j] = 1
		i += 1
		j = (j + 1) % n
		if i == n:
			i = 0
			j = (j + 1) % n
	print(fin)
	for i in mat:
		for j in i:
			print(j, end='')
		print()


import sys, io, os, time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
input = sys.stdin.readline
for ii in range(int(input())):
	(n, k) = map(int, input().split())
	ok = k
	arr = [['0'] * n for i in range(n)]
	for i in range(n):
		for j in range(n):
			if k > 0:
				k -= 1
				arr[(i + j) % n][j] = '1'
	if ok % n == 0:
		print(0)
	else:
		print(2)
	for i in arr:
		print(''.join(i))


def main():
	(n, k) = map(int, input().split(' '))
	A = []
	if k < n * n // 2:
		f1 = '1'
		f0 = '0'
	else:
		k = n * n - k
		f1 = '0'
		f0 = '1'
	for i in range(n):
		A.append(f0 * n)
	for z in range(k):
		x = z % n
		y = (z % n + z // n) % n
		a = list(A[x])
		a[y] = f1
		A[x] = ''.join(a)
	minR = 0
	maxR = 0
	minC = 0
	maxC = 0
	a = []
	for i in range(n):
		R = sum(map(int, list(A[i])))
		if i == 0:
			minR = R
			maxR = R
		else:
			minR = min(R, minR)
			maxR = max(R, maxR)
	for j in range(n):
		C = 0
		for i in range(n):
			C += int(A[i][j])
		if j == 0:
			minC = C
			maxC = C
		else:
			minC = min(C, minC)
			maxC = max(C, maxC)
	print((maxR - minR) ** 2 + (maxC - minC) ** 2)
	print(*A, sep='\n')
for _ in range(int(input())):
	main()


from collections import Counter
from collections import defaultdict
from collections import deque
import math
import heapq
import sys
import io, os
input = sys.stdin.readline
from bisect import *
rs = lambda : input().strip()
ri = lambda : int(input())
rl = lambda : list(map(int, input().strip().split()))
rls = lambda : list(map(str, input().split()))
t = int(input())
d = defaultdict(lambda : 0)
for _ in range(0, t):
	(n, k) = rl()
	a = []
	for i in range(0, n):
		a.append([0] * n)
	x = 0
	y = 0
	g = 1
	for i in range(0, k):
		a[x][y] = 1
		x = (x + 1) % n
		y = (y + 1) % n
		if x == 0:
			y = g
			g = g + 1
	mx = 0
	mn = 999999
	for i in range(0, n):
		mx = max(mx, sum(a[i]))
		mn = min(mn, sum(a[i]))
	ans = (mx - mn) ** 2
	mx = 0
	mn = 999999
	for i in range(0, n):
		s1 = 0
		for j in range(0, n):
			s1 = s1 + a[j][i]
		mx = max(mx, s1)
		mn = min(mn, s1)
	ans = ans + (mx - mn) ** 2
	print(ans)
	for i in range(0, n):
		for j in range(0, n):
			print(a[i][j], end='')
		print()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	a = [[0] * n for j in range(n)]
	c = [[0] * n for j in range(n)]
	x = 0
	y = 0
	d = dict()
	p = 0
	while k != 0:
		if (x % n, y % n) in d.keys():
			x = 0
			y = p + 1
			p += 1
		a[x % n][y % n] = 1
		d[x % n, y % n] = 1
		x += 1
		y += 1
		k += -1
	for p in range(n):
		for j in range(n):
			c[p][j] = a[j][p]
	min1 = 10 ** 5 + 1
	max1 = -1
	min2 = 10 ** 5 + 1
	max2 = -1
	for i in range(n):
		min1 = min(min1, a[i].count(1))
		max1 = max(max1, a[i].count(1))
		min2 = min(min2, c[i].count(1))
		max2 = max(max2, c[i].count(1))
	k = int((max1 - min1) ** 2) + int(max2 - min2) ** 2
	print(k)
	for j in a:
		for q in j:
			print(q, end='')
		print()


t = int(input())
while t != 0:
	t -= 1
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	(a, b) = (0, 0)
	A = [[0 for _ in range(n)] for _ in range(n)]
	for i in range(k):
		A[a][b] = 1
		a += 1
		b += 1
		if a == n:
			b += 1
		a %= n
		b %= n
	for q in A:
		print(''.join(map(str, q)))


T = int(input())
for t in range(T):
	(n, k) = [int(i) for i in input().split()]
	ans = [[0 for i in range(n)] for j in range(n)]
	row = col = 0
	for i in range(k):
		ans[row][col] = 1
		row += 1
		col += 1
		col %= n
		if row == n:
			row = 0
			col += 1
			col %= n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		tmp = ''
		for j in ans[i]:
			tmp += str(j)
		print(tmp)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = [[0 for i in range(n)] for j in range(n)]
	for i in range(k):
		arr[i % n][(i + i // n) % n] = 1
	lol = []
	lol1 = []
	for i in range(n):
		lol.append(sum(arr[i]))
		s = 0
		for j in range(n):
			s += arr[j][i]
		lol1.append(s)
	lol.sort()
	lol1.sort()
	print((lol[0] - lol[-1]) * (lol[0] - lol[-1]) + (lol1[0] - lol1[-1]) * (lol1[0] - lol1[-1]))
	for i in range(n):
		for j in range(n):
			print(arr[i][j], end='')
		print()


for _ in range(int(input())):
	(n, p) = map(int, input().split())
	matrix = [[0 for i in range(n)] for j in range(n)]
	over = False
	if not over:
		for k in range(n):
			for i in range(n):
				j = i + k
				if p:
					matrix[i][j % n] = 1
					p -= 1
				else:
					over = True
					break
			if over:
				break
	min_row = float('inf')
	max_row = 0
	for i in range(n):
		s = sum(matrix[i])
		min_row = min(min_row, s)
		max_row = max(max_row, s)
	c_max = 0
	c_min = float('inf')
	for i in range(n):
		s = 0
		for j in range(n):
			s += matrix[i][j]
		c_max = max(c_max, s)
		c_min = min(c_min, s)
	print((min_row - max_row) ** 2 + (c_max - c_min) ** 2)
	for row in matrix:
		print(''.join(map(str, row)))


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	for _ in range(int(input())):
		(N, K) = map(int, input().split())
		if K % N == 0:
			print(0)
		else:
			print(2)
		ans = [[0] * N for _ in range(N)]
		cnt = 0
		flg = 0
		for p in range(N):
			if flg:
				break
			for i in range(N):
				if cnt == K:
					flg = 1
					break
				ans[i][(i + p) % N] = 1
				cnt += 1
		for i in range(N):
			print(''.join(map(str, ans[i])))
main()


import sys
input = sys.stdin.readline
T = int(input())
for testcase in range(T):
	(n, k) = map(int, input().split())
	if n == 1:
		print(0)
		if k == 0:
			print('0')
		else:
			print('1')
		continue
	a = [['0'] * n for _ in range(n)]
	idx = []
	for i in range(n):
		idx.append(i * n + i)
	for i in range(1, n):
		for ctr in range(n - i):
			idx.append((i + ctr) * n + ctr)
		for ctr in range(i):
			idx.append(ctr * n + n - i + ctr)
	for i in range(k):
		(x, y) = divmod(idx[i], n)
		a[x][y] = '1'
	f = 0
	(r1, r2, c1, c2) = (0, n, 0, n)
	for i in range(n):
		tr = 0
		tc = 0
		for j in range(n):
			if a[i][j] == '1':
				tr += 1
			if a[j][i] == '1':
				tc += 1
		r1 = max(r1, tr)
		r2 = min(r2, tr)
		c1 = max(c1, tc)
		c2 = min(c2, tc)
	print((r1 - r2) ** 2 + (c1 - c2) ** 2)
	for i in range(n):
		print(''.join(a[i]))


import sys
import heapq

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, sys.stdin.readline().split())
		ans = 0
		if k % n:
			ans = 2
		ansTable = [[0] * n for _ in range(n)]
		for i in range(k):
			ansTable[i % n][(i % n + i // n) % n] = 1
		print(ans)
		for i in range(n):
			for j in range(n):
				print(ansTable[i][j], end='')
			print('')
	return
main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = max(sum_so_far, current_sum)
	return sum_so_far
from math import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0 for i in range(n)] for i in range(n)]
	c = -1
	for i in range(k):
		if i % n == 0:
			c += 1
		mat[i % n][c % n] = 1
		c += 1
	print(2 if k % n else 0)
	for i in range(n):
		print(''.join((str(x) for x in mat[i])))


cases = int(input())
for t in range(cases):
	(n, k) = list(map(int, input().split()))
	if k % n == 0:
		print(0)
	else:
		print(2)
	a = [['1'] * n for i in range(n)]
	d = {i: i for i in range(n)}
	for i in range(n ** 2 - k):
		row = i % n
		col = d[row]
		d[row] = (col + 1) % n
		a[row][col] = '0'
	for i in a:
		print(''.join(i))


q = int(input())
for _ in range(q):
	(n, k) = list(map(int, input().split()))
	odp = [[0] * n for i in range(n)]
	cur = [0, 0]
	zap = 0
	while True:
		if zap >= k:
			break
		odp[cur[0]][cur[1]] = 1
		zap += 1
		cur[0] = (cur[0] + 1) % n
		cur[1] = (cur[1] + 1) % n
		if cur[0] == 0:
			cur[1] = zap // n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(list(map(str, odp[i]))))


t = int(input())
for o in range(t):
	l = str.split(input(), ' ')
	n = int(l[0])
	k = int(l[1])
	x = k // n
	r = k % n
	if r == 0:
		a = 0
	else:
		a = 2
	print(a)
	s = '1' * x + '0' * (n - x)
	for i in range(n):
		Rfirst = s[0:len(s) - i]
		Rsecond = s[len(s) - i:]
		final = Rsecond + Rfirst
		if r > 0:
			r = r - 1
			final = list(final)
			final[(i + x) % n] = '1'
			final = ''.join(final)
		print(final)


for xyz in range(0, int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	ci = []
	for i in range(0, n):
		ci.append(i)
	ans = [[0] * n for _ in range(n)]
	cr = 0
	c = 0
	while c != k:
		ans[cr][ci[cr]] = 1
		ci[cr] = (ci[cr] + 1) % n
		cr = (cr + 1) % n
		c += 1
	for i in range(0, n):
		for j in range(0, n):
			print(ans[i][j], end='')
		print('')


import os
import sys
from io import BytesIO, IOBase
import math

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for xyz in range(0, int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
		for i in range(0, n):
			ans = ['0'] * n
			for j in range(i, i + k // n):
				ans[j % n] = '1'
			ans = ''.join(ans)
			print(ans)
	else:
		print(2)
		for i in range(0, k % n):
			ans = ['0'] * n
			for j in range(i, 1 + i + k // n):
				ans[j % n] = '1'
			ans = ''.join(ans)
			print(ans)
		for i in range(k % n, n):
			ans = ['0'] * n
			for j in range(i, i + k // n):
				ans[j % n] = '1'
			ans = ''.join(ans)
			print(ans)


t = int(input())
for s in range(t):
	(n, m) = map(int, input().split())
	d = m // n
	r = m % n
	array = [d for i in range(n)]
	matrix = [[0 for i in range(n)] for j in range(n)]
	visited = [[0, i] for i in range(n)]
	for i in range(n):
		visited.sort()
		if i >= 0 and i < r:
			for j in range(array[i] + 1):
				visited[j][0] += 1
				matrix[i][visited[j][1]] = 1
		else:
			for j in range(array[i]):
				visited[j][0] += 1
				matrix[i][visited[j][1]] = 1
	if m % n == 0:
		print(0)
	else:
		print(2)
	for i in matrix:
		for j in i:
			print(j, end='')
		print()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	m = [[0 for i in range(n)] for i in range(n)]
	(i, j) = (0, 0)
	for x in range(k):
		m[i][j] = 1
		(i, j) = (i + 1, (j + 1) % n)
		if i == n:
			i = 0
			j = (j + 1) % n
	ans = 2 if k % n else 0
	print(ans)
	for l in m:
		print(''.join((str(p) for p in l)))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n:
		print(2)
	else:
		print(0)
	ans = [[0] * n for i in range(n)]
	now = 0
	count = 0
	i = 0
	while count < k:
		if now < n:
			ans[now][(now + i) % n] = 1
			now += 1
			count += 1
		else:
			now = 0
			i += 1
	for i in ans:
		print(*i, sep='')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = []
	for i in range(n):
		B = []
		for j in range(n):
			B.append(0)
		A.append(B)
	z = 0
	while k > 0:
		for i in range(n):
			if k > 0:
				A[(z + i) % n][i] = 1
				k -= 1
		z += 1
	C1 = []
	C2 = []
	for i in range(n):
		C1.append(sum(A[i]))
	for i in range(n):
		yy = 0
		for j in range(n):
			yy += A[j][i]
		C2.append(yy)
	print((max(C1) - min(C1)) ** 2 + (max(C2) - min(C2)) ** 2)
	for a in A:
		for b in a:
			print(b, end='')
		print()


from math import ceil
T = int(input().rstrip())
for tt in range(T):
	(n, r) = list(map(int, input().rstrip().split(' ')))
	arr = [[0] * n for i in range(n)]
	dpr = [0] * n
	dpc = [0] * n
	i = 0
	j = 0
	tp = 0
	for ind in range(r):
		arr[i][j] = 1
		dpr[i] += 1
		dpc[j] += 1
		if i + 1 < n and j + 1 < n:
			i += 1
			j += 1
		elif i + 1 == n:
			i = 0
			tp += 1
			j = tp
		elif j + 1 == n:
			j = 0
			i += 1
	cnt = (max(dpr) - min(dpr)) ** 2 + (max(dpc) - min(dpc)) ** 2
	print(cnt)
	for i in arr:
		print(*i, sep='')


from math import *
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	ans = 0
	if k % n != 0:
		ans = 2
	print(ans)
	i = 0
	j = 0
	arr = []
	for x in range(n):
		arr.append([0] * n)
	while k > 0:
		arr[i][j] = 1
		k -= 1
		i += 1
		j = (j + 1) % n
		if i >= n:
			i = 0
			j = (j + 1) % n
	for z in range(n):
		for l in range(n):
			print(arr[z][l], end='')
		print()


t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	upper = (k + n - 1) // n
	lower = k // n
	loss = (upper - lower) ** 2 * 2
	print(loss)
	arr = [['0' for __ in range(n)] for ___ in range(n)]
	startCol = 0
	zz = 0
	for __ in range(k):
		arr[zz][(startCol + zz) % n] = '1'
		zz += 1
		if zz == n:
			startCol += 1
			zz = 0
	for row in arr:
		print(''.join(row))


def fa(ll, nn):
	an1 = 0
	an2 = 0
	k = nn
	for i in range(k):
		an1 += ll[i][0]
		an2 += ll[i][k - 1]
	print((an2 - an1) ** 2 * 2)

def pr(j):
	fa(j, len(j))
	for i in j:
		print(*i, sep='')

def solve():
	(n, k) = map(int, input().split())
	lst = [[0 for i in range(n)] for j in range(n)]
	for y in range(n):
		for x in range(n):
			if k == 0:
				pr(lst)
				return
			lst[(y + x) % n][x] = 1
			k -= 1
	pr(lst)
for i in range(int(input())):
	solve()


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	(n, k) = mints()
	a = [None] * n
	R = [0] * n
	C = [0] * n
	for i in range(n):
		a[i] = [0] * n
	z = 0
	for j in range(0, k, n):
		for i in range(min(n, k - j)):
			a[i][(z + i) % n] = 1
			C[i] += 1
			R[(z + i) % n] += 1
		z += 1
	print((max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2)
	for i in a:
		print(''.join(map(str, i)))
for i in range(mint()):
	solve()


t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	k = int(l[1])
	arr = [[0 for i in range(n)] for i in range(n)]
	q = k // n
	rem = k % n
	for i in range(rem):
		for u in range(q + 1):
			arr[i][(i + u) % n] = 1
	for i in range(rem, n):
		for u in range(q):
			arr[i][(i + u) % n] = 1
	if rem == 0:
		print(0)
		for i in range(n):
			for j in range(n):
				print(arr[i][j], end='')
			print()
	else:
		print(2)
		for i in range(n):
			for j in range(n):
				print(arr[i][j], end='')
			print()


t = int(input())
for ii in range(t):
	(n, k) = map(int, input().split())
	mat = []
	for i in range(n):
		temp = [0] * n
		mat.append(temp)
	count = k
	for i in range(n):
		for j in range(n):
			z = (j + i) % n
			if count > 0:
				mat[j][z] = 1
				count -= 1
			else:
				break
		if count == 0:
			break
	rowMax = 0
	rowMin = n
	for i in range(n):
		s = sum(mat[i])
		if s < rowMin:
			rowMin = s
		if s > rowMax:
			rowMax = s
	colMax = 0
	colMin = n
	for i in range(n):
		s = 0
		for j in range(n):
			s += mat[j][i]
		if s < colMin:
			colMin = s
		if s > colMax:
			colMax = s
	fa = (rowMax - rowMin) ** 2 + (colMax - colMin) ** 2
	print(fa)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print()


def solution(n, k):
	mat = [[0] * n for i in range(n)]
	i = 0
	j = 0
	while k > 0:
		if i < n and j < n:
			if mat[i][j] == 0:
				mat[i][j] = 1
				i = i + 1
				j = j + 1
				k = k - 1
			else:
				i = i + 1
		elif i == n and j == n:
			i = 1
			j = 0
		elif i == n:
			i = 0
		elif j == n:
			j = 0
	return mat
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	f = 0
	r = k % n
	if r == 0:
		f = 0
	else:
		f = 2
	ans = solution(n, k)
	print(f)
	for i in ans:
		for j in i:
			print(j, end='')
		print()


from collections import Counter
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()
for _ in range(t):
	(n, k) = gil()
	p = list(range(n))
	r = 0
	mat = [[0 for _ in range(n)] for _ in range(n)]
	while k:
		mat[r][p[r]] = 1
		p[r] = (p[r] + 1) % n
		r = (r + 1) % n
		k -= 1
	ans = 0
	(ma, mi) = (-inf, inf)
	for m in mat:
		v = sum(m)
		ma = max(ma, v)
		mi = min(mi, v)
	ans += (ma - mi) ** 2
	(ma, mi) = (-inf, inf)
	for m in zip(*mat):
		v = sum(m)
		ma = max(ma, v)
		mi = min(mi, v)
	ans += (ma - mi) ** 2
	print(ans)
	for m in mat:
		for v in m:
			print(v, end='')
		print()


for t in range(int(input())):
	(n, k) = map(int, input().split())
	matrix = []
	for i in range(n):
		a = []
		for i in range(n):
			a.append(0)
		matrix.append(a)
	if k % n == 0:
		f = 0
	else:
		f = 2
	i = 0
	j = 0
	s = 0
	while k > 0:
		matrix[i % n][j % n] += 1
		i += 1
		j += 1
		s += 1
		if s % n == 0:
			i = s // n
			j = 0
		k -= 1
	print(f)
	for i in range(n):
		print(''.join((str(x) for x in matrix[i])))


from sys import stdin
input = stdin.readline

def main():
	test = int(input())
	for _ in range(test):
		(n, k) = [int(i) for i in input().split(' ')]
		matrix = [[0 for i in range(n)] for i in range(n)]
		col = k // n
		row = k % n
		ans = 0
		if row != 0:
			ans = 2
		for i in range(n):
			temp = col
			if row > 0:
				row -= 1
				temp += 1
			j = i
			while temp > 0:
				matrix[i][j] = 1
				j += 1
				temp -= 1
				if j == n:
					j = 0
		print(ans)
		for i in matrix:
			for j in i:
				print(j, end='')
			print()
main()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(''.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	(n, k) = sp()
	answer = [[0] * n for i in range(n)]
	temp = k // n
	if k % n:
		temp += 1
	(i, j) = (0, 0)
	s = set()
	old = k
	cnt = 0
	while k:
		if temp * cnt + (temp - 1) * (n - cnt) == old:
			temp -= 1
		cnt += 1
		while j in s:
			j = (j + 1) % n
		s.add(j)
		for res in range(temp):
			answer[i][j] = 1
			j = (j + 1) % n
			k -= 1
		i += 1
	cnt = 0
	if old % n:
		cnt += 2
	out(cnt)
	for i in answer:
		out(*i)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n:
		print(2)
	else:
		print(0)
	ans = [[0 for i in range(n)] for j in range(n)]
	if k == 0:
		for i in ans:
			print(*i, sep='')
		continue
	for i in range(n):
		for j in range(n):
			ans[j][(i + j) % n] = 1
			k -= 1
			if k == 0:
				break
		else:
			continue
		break
	for i in ans:
		print(*i, sep='')


from sys import stdin
input = stdin.readline
import bisect
import math
for xoxo in range(1):
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		(r, c) = ([0] * n, [0] * n)
		a = [[1 for i in range(n)] for j in range(n)]
		k = n * n - k
		i = 0
		(j, s) = (0, 0)
		while i < k:
			j = (i % n + i // n) % n
			a[i % n][j] = 0
			i += 1
		for i in range(n):
			for j in range(n):
				if a[i][j] == 1:
					r[i] += 1
					c[j] += 1
		print((max(c) - min(c)) ** 2 + (max(r) - min(r)) ** 2)
		for i in range(n):
			for j in range(n):
				print(a[i][j], end='')
			print()


import sys
input = sys.stdin.readline

def ceil(x, y):
	return (x + y - 1) // y

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(10000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	(n, k) = int_array()
	k_ = k
	ans = [['0' for _ in range(n)] for __ in range(n)]
	for i in range(n):
		(x, y) = (0, i)
		if not k:
			break
		for _ in range(n):
			if not k:
				break
			ans[x][y] = '1'
			x += 1
			y = (y + 1) % n
			k -= 1
	if k_ % n == 0:
		print(0)
	else:
		print(2)
	for i in ans:
		print(''.join(i))


t = int(input())
cnt = 0
while cnt < t:
	cnt += 1
	res = 0
	(n, k) = [int(i) for i in input().split()]
	a = [[0] * n for i in range(n)]
	if k == 0:
		res = 0
	elif k < n:
		res = 2
		for i in range(k):
			a[i][i] = 1
	elif k % n == 0:
		res = 0
		for i in range(n):
			for j in range(i, k // n + i):
				a[i][j % n] = 1
	else:
		rem = k % n
		res = 2
		for i in range(rem):
			for j in range(i, i + k // n + 1):
				a[i][j % n] = 1
		for i in range(rem, n):
			for j in range(i, i + k // n):
				a[i][j % n] = 1
	print(res)
	for row in a:
		print(''.join((str(i) for i in row)))


for __ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	ans = [[0] * n for i in range(n)]
	(i, j) = (0, 0)
	while k > 0:
		while i < n and k > 0:
			ans[i][j] = 1
			i += 1
			j += 1
			k -= 1
			j %= n
		i = 0
		j += 1
	(a1, a2, b1, b2) = (10 ** 9, 0, 10 ** 9, 0)
	for i in range(n):
		a1 = min(a1, ans[i].count(1))
		a2 = max(a2, ans[i].count(1))
	for i in range(n):
		kek1 = 0
		for j in range(n):
			if ans[j][i] == 1:
				kek1 += 1
		b1 = min(b1, kek1)
		b2 = max(b2, kek1)
	print((a2 - a1) ** 2 + (b2 - b1) ** 2)
	for elem in ans:
		print(''.join(map(str, elem)))


import sys
import math
import collections
from sys import stdin, stdout, setrecursionlimit
import bisect as bs
setrecursionlimit(2 ** 20)
M = 10 ** 9 + 7
T = int(stdin.readline())
for _ in range(T):
	(n, k) = list(map(int, stdin.readline().split()))
	m = []
	for i in range(n):
		m.append([0] * n)
	q = k // n
	r = k % n
	for i in range(q):
		for j in range(n):
			m[(i + j) % n][j] = 1
	i = q
	for j in range(r):
		m[(i + j) % n][j] = 1
	ans = 2 if r > 0 else 0
	print(ans)
	for i in range(n):
		for j in range(n):
			print(m[i][j], end='')
		print('')


for t in range(int(input())):
	(n, m) = map(int, input().split())
	rem = 0
	if m % n:
		rem = 1
	ans = 2 * rem ** 2
	mat = ['0' * n] * n
	st = '1' * (m // n) + '0' * (n - m // n)
	for i in range(n):
		mat[i] = st[i:] + st[:i]
	for i in range(m % n):
		mat[i] = mat[i][:n - 1 - i] + '1' + mat[i][n - i:]
	print(ans)
	for i in range(n):
		print(mat[i])


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	equal = k // n
	remained = k % n
	mat = [[0 for _ in range(n)] for _ in range(n)]
	col = 0
	arr = [equal for i in range(n)]
	for i in range(remained):
		arr[-i - 1] += 1
	if remained == 0:
		diff_square = 0
	else:
		diff_square = 2
	for i in range(n):
		for _ in range(arr[i]):
			mat[i][col] = 1
			col = (col + 1) % n
	print(diff_square)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print()


from sys import stdin, stdout

def grid_00100(n, k):
	a = [[0 for j in range(n)] for i in range(n)]
	f = 0 if k == 0 or k % n == 0 else 2
	i = j = 0
	while k > 0:
		a[i][j] = 1
		i += 1
		j += 1
		j %= n
		if i == n:
			i = 0
			j += 1
			j %= n
		k -= 1
	return [f, a]
t = int(stdin.readline())
for i in range(t):
	(n, k) = map(int, stdin.readline().split())
	ans = grid_00100(n, k)
	stdout.write(str(ans[0]) + '\n')
	for j in range(n):
		stdout.write(''.join(map(str, ans[1][j])) + '\n')


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	if k % n == 0:
		print(0)
	else:
		print(2)
	a = [['0' for i in range(n)] for r in range(n)]
	for i in range(k // n):
		for r in range(n):
			a[r][(r + i) % n] = '1'
	for i in range(k % n):
		a[i][(i + k // n) % n] = '1'
	for i in range(n):
		print(''.join(a[i]))


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]
for q in range(II()):
	(n, k) = MI()
	i = j = 0
	aa = [[0] * n for _ in range(n)]
	for _ in range(k):
		if j == n:
			j = 0
		if i == n:
			(i, j) = (0, j + 1)
		aa[i][j] = 1
		(i, j) = (i + 1, j + 1)
	if k % n:
		print(2)
	else:
		print(0)
	for row in aa:
		print(*row, sep='')


t = int(input())
while t > 0:
	(n, k) = [int(ele) for ele in input().split()]
	matrix = [[0 for i in range(n)] for j in range(n)]
	if k < n:
		i = 0
		if k == 0:
			print(0)
		else:
			print(2)
		for i in range(k):
			matrix[i][i] = 1
		for i in range(n):
			for j in range(n):
				print(matrix[i][j], end='')
			print()
	elif k == n * n:
		print(0)
		for i in range(n):
			for j in range(n):
				print(1, end='')
			print()
	else:
		div = k // n
		index = 0
		for i in range(n):
			j = index % n
			x = div
			while x > 0:
				if j != index:
					matrix[i][j] = 1
					x -= 1
				j = (j + 1) % n
			index += 1
		rem = k % n
		if rem == 0:
			print(0)
		else:
			print(2)
			index = 0
			while rem > 0:
				matrix[index][index] = 1
				index += 1
				rem -= 1
		for i in range(n):
			for j in range(n):
				print(matrix[i][j], end='')
			print()
	t -= 1


from sys import stdin, stdout
ans = []
raw = stdin.read().split('\n')
testcase = raw[0]
for test in range(int(testcase)):
	(n, k) = map(int, raw[test + 1].split())
	ans += [str(2 if k % n else 0)]
	grid = [[0] * n for _ in range(n)]
	for i in range(n):
		if k == 0:
			break
		grid[i][i] = 1
		k -= 1
	else:
		for i in range(n - 1):
			(x, y) = (n - 1 - i, 0)
			for j in range(x, n):
				if k:
					grid[x][y] = 1
					x += 1
					y += 1
					k -= 1
				else:
					break
			(x, y) = (0, i + 1)
			for j in range(i + 1, n):
				if k:
					grid[x][y] = 1
					x += 1
					y += 1
					k -= 1
				else:
					break
			if not k:
				break
	for i in range(n):
		ans += [''.join(map(str, grid[i]))]
ans = '\n'.join(ans)
stdout.write(ans)


t = int(input())
while t != 0:
	(n, k) = map(int, input().split())
	list1 = [[0 for i in range(n)] for j in range(n)]
	(i, j) = (0, 0)
	ans = 0
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	for _ in range(k):
		list1[i][j] = 1
		i += 1
		j = (j + 1) % n
		if i == n:
			i = 0
			j = (j + 1) % n
	print(ans)
	for i in list1:
		for j in i:
			print(j, end='')
		print()
	t -= 1


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	cnt = n ** 2 - k
	a = []
	cnt //= n
	for i in range(n):
		b = [1] * n
		a.append(b)
	for i in range(n):
		for j in range(i, cnt + i):
			if j < n:
				a[i][j] = 0
			else:
				a[i][j - n] = 0
	count = n ** 2 - k - cnt * n
	for i in range(count):
		j = cnt + i
		if j < n:
			a[i][j] = 0
		else:
			a[i][j - n] = 0
	c = []
	for i in range(n):
		c.append(sum(a[i]))
	d = []
	for i in range(n):
		sums = 0
		for j in range(n):
			sums += a[j][i]
		d.append(sums)
	ans = (max(c) - min(c)) ** 2 + (max(d) - min(d)) ** 2
	print(ans)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


def calc(matrix):
	row_max = max((sum(row) for row in matrix))
	row_min = min((sum(row) for row in matrix))
	col_max = max((sum(row) for row in zip(*matrix)))
	col_min = min((sum(row) for row in zip(*matrix)))
	return (row_max - row_min) ** 2 + (col_max - col_min) ** 2
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	matrix = [[0] * n for _ in range(n)]
	for i in range(min(k, n)):
		matrix[i][i] = 1
	k -= min(k, n)
	row_idx_start = 1
	col_idx_start = n - 1
	switch = True
	while k:
		if switch:
			row_idx = row_idx_start
			col_idx = 0
		else:
			row_idx = 0
			col_idx = col_idx_start
		while k and row_idx < n and (col_idx < n):
			assert matrix[row_idx][col_idx] == 0
			matrix[row_idx][col_idx] = 1
			row_idx += 1
			col_idx += 1
			k -= 1
		if switch:
			row_idx_start += 1
		else:
			col_idx_start -= 1
		switch = not switch
	print(calc(matrix))
	for row in matrix:
		print(''.join(map(str, row)))


from sys import stdin, stdout
import sys
from math import *

def compute(ar):
	mn = inf
	mx = 0
	for i in range(n):
		s = sum(ar[i])
		if s > mx:
			mx = s
		if s < mn:
			mn = s
	ans = (mx - mn) ** 2
	mn = inf
	mx = 0
	for i in range(n):
		s = 0
		for j in range(n):
			s += ar[i][j]
		s = sum(ar[i])
		if s > mx:
			mx = s
		if s < mn:
			mn = s
	return ans + (mx - mn) ** 2
for __ in range(int(input())):
	(n, k) = map(int, input().split())
	r = n * n - k
	ans = []
	for i in range(n):
		ans.append([1] * n)
	if r == 0:
		print(0)
		for i in range(n):
			print(''.join(list(map(str, ans[i]))))
	else:
		while r > 0:
			x = 0
			for i in range(n):
				if ans[0][i] == 1:
					x = i
					break
			for i in range(n):
				ans[i][x % n] = 0
				x += 1
				r -= 1
				if r == 0:
					break
		rslt = compute(ans)
		print(rslt)
		for i in range(n):
			print(''.join(list(map(str, ans[i]))))


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	(n, k) = rinput()
	mat = [[0 for i in range(n)] for i in range(n)]
	onesinrow = k // n
	temp = [1] * onesinrow + [0] * (n - onesinrow)
	for i in range(n):
		mat[i] = temp[-i:] + temp[:-i]
	left = k % n
	for i in range(n):
		if left == 0:
			break
		mat[i][(i + onesinrow) % n] = 1
		left -= 1
	(minr, minc) = (float('inf'), float('inf'))
	(maxr, maxc) = (-float('inf'), -float('inf'))
	for i in range(n):
		maxr = max(maxr, mat[i].count(1))
		minr = min(minr, mat[i].count(1))
	for j in range(n):
		count = 0
		for i in range(n):
			if mat[i][j] == 1:
				count += 1
		maxc = max(maxc, count)
		minc = min(minc, count)
	print((minr - maxr) ** 2 + (minc - maxc) ** 2)
	for i in range(n):
		print(''.join(map(str, mat[i])))


t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	if k % n == 0:
		print(0)
	else:
		print(2)
	list_r = [k // n for r in range(n)]
	for idx in range(k % n):
		list_r[idx] += 1
	for r in range(n):
		row = ''
		front_idx = 0
		if list_r[r] > n - r:
			front_idx = list_r[r] - (n - r)
		count = 0
		final = list_r[r]
		for c in range(n):
			if final > count:
				if c < front_idx:
					row += '1'
					count += 1
				elif c < r:
					row += '0'
				else:
					row += '1'
					count += 1
			else:
				row += '0'
		print(row)


import sys
from collections import defaultdict, deque, Counter
import math
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
getS = lambda : input().strip()
getN = lambda : int(input())
getList = lambda : list(map(int, input().split()))
getZList = lambda : [int(x) - 1 for x in input().split()]
INF = 10 ** 20
MOD = 10 ** 9 + 7
divide = lambda x: pow(x, MOD - 2, MOD)

def era(n):
	ret = [1 for i in range(n + 2)]
	for i in range(2, int(math.sqrt(n) + 3)):
		if ret[i] != 0:
			for j in range(2, n // i + 1):
				ret[i * j] = 0
	rret = []
	for (i, r) in enumerate(ret):
		if r == 1 and i != 0:
			rret.append(i)
	return rret

def houjyo(n, m, k, kaijyo):
	if k == n:
		return 1
	else:
		ret = nck(n, k, kaijyo) * npk(m - k, n - k, kaijyo)
		return ret % MOD

def nck(n, k, kaijyo):
	return npk(n, k, kaijyo) * divide(kaijyo[k]) % MOD

def npk(n, k, kaijyo):
	if k == 0 or k == n:
		return n % MOD
	return kaijyo[n] * divide(kaijyo[n - k]) % MOD

def kaijyo(n):
	ret = [1]
	for i in range(1, n + 1):
		ret.append(ret[-1] * i % MOD)
	return ret

def solve():
	(n, k) = getList()
	hosyo = k // n
	amari = k % n
	if amari == 0:
		print(0)
	else:
		print(2)
	d1 = deque(list('1' * hosyo + '0' * (n - hosyo)))
	d2 = deque(list('1' * (hosyo + 1) + '0' * (n - hosyo - 1)))
	for i in range(n):
		if i < amari:
			print(''.join(d2))
		else:
			print(''.join(d1))
		da = d2.popleft()
		d2.append(da)
		db = d1.popleft()
		d1.append(db)

def main():
	n = getN()
	for _ in range(n):
		solve()
main()


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(a, b) = map(int, input().split())
	c = [[0] * a for x in range(a)]
	(x, y) = (0, 0)
	cnt = 0
	ans = []
	while True:
		if cnt == b:
			break
		cnt += 1
		c[x][y] = 1
		x += 1
		y += 1
		if x == a:
			x = 0
			y += 1
		y %= a
	for x in c:
		ans.append(sum(x))
	print(2 * (max(ans) - min(ans)) ** 2)
	for x in c:
		for y in x:
			print(y, end='')
		print()


for ii in range(int(input())):
	(n, k) = map(int, input().split())
	ma = [['0' for i in range(n)] for j in range(n)]
	flag = True
	for i in range(n):
		x = 0
		y = i
		for j in range(n):
			if k > 0:
				ma[(x + j) % n][(y + j) % n] = '1'
				k -= 1
			if k <= 0:
				flag = False
				break
		if not flag:
			break
	rs = []
	cs = []
	for i in range(n):
		rs.append(sum([int(p) for p in ma[i]]))
		c = 0
		for j in range(n):
			c += int(ma[i][j])
		cs.append(c)
	print((max(rs) - min(rs)) ** 2 + (max(cs) - min(cs)) ** 2)
	for i in range(n):
		print(''.join(ma[i]))


import math

def read_int():
	return int(input().strip())

def read_ints():
	return list(map(int, input().strip().split(' ')))

def solve():
	(n, k) = read_ints()
	table = [['0'] * n for _ in range(n)]
	cols = [k // n + (1 if k % n > i else 0) for i in range(n)]
	col_indexes = [i for i in range(n)]
	for i in range(k):
		table[i % n][col_indexes[i % n] % n] = '1'
		col_indexes[i % n] += 1
	(min_R, max_R) = (math.inf, 0)
	(min_C, max_C) = (math.inf, 0)
	for i in range(n):
		R = sum((int(table[i][j]) for j in range(n)))
		min_R = min(min_R, R)
		max_R = max(max_R, R)
	for j in range(n):
		C = sum((int(table[i][j]) for i in range(n)))
		min_C = min(min_C, C)
		max_C = max(max_C, C)
	print((max_R - min_R) ** 2 + (max_C - min_C) ** 2)
	for row in table:
		print(''.join(row))
T = read_int()
for _ in range(T):
	solve()


def mitao(x):
	(nx, ny) = (0, 0)
	for _ in range(x):
		for i in range(n):
			grid[nx % n][ny % n] = '0'
			nx += 1
			ny += 1
		ny += 1
	return [nx, ny]
for _ in range(int(input())):
	(n, m) = map(int, input().split())
	grid = [['1' for _ in range(n)] for _ in range(n)]
	k = n * n - m
	t = k // n
	r = k % n
	(nx, ny) = mitao(t)
	for i in range(r):
		grid[nx % n][ny % n] = '0'
		nx += 1
		ny += 1
	if r == 0:
		print(0)
	else:
		print(2)
	for i in grid:
		print(''.join(i))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = [[0] * n for i in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	i = 0
	j = 0
	c = 0
	d = 0
	while k != 0:
		if d % n == 0:
			j = c
			c += 1
		i %= n
		j %= n
		arr[i][j] = 1
		i += 1
		j += 1
		k -= 1
		d += 1
	for i in range(n):
		for j in range(n):
			print(arr[i][j], end='')
		print()


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().rstrip().split(' '))
	complete = k // n
	remaining = k % n
	if remaining > 0:
		print(2)
	else:
		print(0)
	for i in range(n):
		out = ['0'] * n
		for j in range(complete):
			out[(j + i) % n] = '1'
		if remaining:
			out[(i + complete) % n] = '1'
			remaining -= 1
		print(''.join(out))


for i in range(int(input())):
	(n, k) = map(int, input().split())
	L = []
	for i in range(n):
		L.append([0] * n)
	c = k // n
	for j in range(n):
		for h in range(c):
			L[j][(j + h) % n] = 1
	for j in range(k % n):
		L[j][(j + c) % n] = 1
	if k % n:
		print(2)
	else:
		print(0)
	for x in L:
		print(*x, sep='')


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	l = []
	for i in range(n):
		L = [0] * n
		l.append(L)
	c = 0
	if k != 0:
		for i in range(n):
			for j in range(n):
				x = j
				y = (i + j) % n
				l[x][y] = 1
				c += 1
				if c == k:
					break
			if c == k:
				break
	for i in range(n):
		for j in range(n):
			print(l[i][j], end='')
		print()


import sys, os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0 for i in range(n)] for j in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	p = 0
	q = 0
	for i in range(k):
		a[p][q] = 1
		p += 1
		q += 1
		q = q % n
		if p == n:
			p = 0
			q = (q + 1) % n
	for i in range(n):
		print(*a[i], sep='')


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().strip().split()))
	list1 = []
	for _ in range(n):
		temp = []
		for _ in range(n):
			temp.append(0)
		list1.append(temp)
	x = 0
	count = 0
	b = 1
	while b:
		for i in range(n):
			if count == k:
				b = 0
				break
			list1[i][(i + x) % n] = 1
			count += 1
		x += 1
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	print(ans)
	for i in range(n):
		for j in range(n):
			print(list1[i][j], end='')
		print()


from sys import stdin, stdout
from bisect import bisect, bisect_left, bisect_right

def gt():
	return map(int, stdin.readline().split())

def gi():
	return int(stdin.readline())

def gl():
	return list(map(int, stdin.readline().split()))

def gs():
	return stdin.readline()
from heapq import heappush, heappop
t = gi()
for _ in range(t):
	(n, k) = gt()
	(r, c) = (0, 0)
	a = [[0 for i in range(n)] for j in range(n)]
	rows = [0] * n
	columns = [0] * n
	while k > 0:
		if a[r][c] == 1:
			while a[r][c] == 1:
				c = (c + 1) % n
		a[r][c] = 1
		rows[r] += 1
		columns[c] += 1
		r = (r + 1) % n
		c = (c + 1) % n
		k -= 1
	(minr, minc) = (n + 1, n + 1)
	(maxr, maxc) = (0, 0)
	for i in range(n):
		minr = min(rows[i], minr)
		maxr = max(rows[i], maxr)
		minc = min(columns[i], minc)
		maxc = max(columns[i], maxc)
	print((maxr - minr) ** 2 + (maxc - minc) ** 2)
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


import math
r = int(input())
for i in range(r):
	(n, k) = map(int, input().split())
	m = [[0 for i in range(n)] for i in range(n)]
	if n ** 2 == k:
		print(0)
		for i in range(n):
			for j in range(n):
				m[i][j] = 1
		for i in range(n):
			print(''.join(map(str, m[i])))
	elif k == n:
		print(0)
		for i in range(n):
			for j in range(n):
				if i == j:
					m[i][j] = 1
		for i in range(n):
			print(''.join(map(str, m[i])))
	elif k % n == 0:
		print(0)
		f = 0
		s = 0
		for i in range(k):
			m[f][s] = 1
			f = f + 1
			s = (s + 1) % n
			if f == n:
				f = 0
				s = (s + 1) % n
		for i in range(n):
			print(''.join(map(str, m[i])))
	else:
		print(2)
		f = 0
		s = 0
		for i in range(k):
			m[f][s] = 1
			f = f + 1
			s = (s + 1) % n
			if f == n:
				f = 0
				s = (s + 1) % n
		for i in range(n):
			print(''.join(map(str, m[i])))


import sys
input = sys.stdin.readline
for f in range(int(input())):
	(n, k) = list(map(int, input().split()))
	sm = k // n
	bg = sm
	toad = k % n
	if toad != 0:
		bg += 1
	print(2 * (bg - sm) ** 2)
	for i in range(n):
		line = ''
		for j in range(n):
			x = i + j
			x %= n
			if x <= sm:
				if x < sm or i < toad:
					line += '1'
				else:
					line += '0'
			else:
				line += '0'
		print(line)


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	(n, k) = map(int, input().split())
	ll = [[0] * n for i in range(n)]
	for j in range(n):
		for i in range(n):
			if k == 0:
				break
			ll[i][(i + j) % n] = 1
			k -= 1
		if k == 0:
			break
	mi = 1000000000000
	mx = 0
	for i in range(n):
		x = sum(ll[i])
		mx = max(mx, x)
		mi = min(mi, x)
	ans = (mx - mi) ** 2
	mx = 0
	mi = 10000000000000
	for j in range(n):
		su = 0
		for i in range(n):
			su += ll[i][j]
		mx = max(mx, su)
		mi = min(mi, su)
	ans += (mx - mi) ** 2
	print(ans)
	for i in ll:
		print(*i, sep='')
	t -= 1


from collections import defaultdict
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = [['0'] * n for i in range(n)]
	flag = False
	dic = defaultdict(bool)
	for i in range(n):
		left = i
		right = 0
		while not dic[left, right]:
			if k == 0:
				flag = True
				break
			dic[left, right] = True
			arr[left][right] = '1'
			k -= 1
			left += 1
			right += 1
			left %= n
			right %= n
		if flag:
			break
	for i in range(n):
		arr[i] = ''.join(arr[i])
	row = []
	col = []
	for i in arr:
		row.append(i.count('1'))
	for i in range(n):
		temp = ''
		for j in range(n):
			temp += arr[j][i]
		col.append(temp.count('1'))
	ans = (max(row) - min(row)) ** 2 + (max(col) - min(col)) ** 2
	print(ans)
	for i in arr:
		print(i)


import sys
input = sys.stdin.buffer.readline

def print(val):
	sys.stdout.write(val + '\n')

def prog():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		if k % n == 0:
			print('0')
		else:
			print('2')
		output = [['0'] * n for i in range(n)]
		i = j = 0
		for a in range(k):
			output[i][j] = '1'
			i += 1
			j = (j + 1) % n
			if i == n:
				i = 0
				j = (j + 1) % n
		for row in output:
			print(''.join(row))
prog()


def cycle(s, n):
	return s[-1] + s[0:n - 1]
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k == n ** 2:
		print(0)
		for i in range(n):
			print('1' * n)
	else:
		if k % n == 0:
			print(0)
		else:
			print(2)
		p = 0
		per = k % n
		count = k // n + 1
		per = k % n
		s = '1' * count + '0' * (n - count)
		for i in range(per):
			print(s)
			s = cycle(s, n)
		if s[-1] == '1':
			if s[0] == '1':
				i = 0
				while s[i] == '1':
					i += 1
					if i == n:
						i = n - 1
						break
				if s[i] == '0':
					i -= 1
			else:
				i = n - 1
		else:
			i = s.find('1' * count)
			i = i + count - 1
		a = ''
		for j in range(n):
			if i == j:
				a = a + '0'
			else:
				a = a + s[j]
		for i in range(n - per):
			print(a)
			a = cycle(a, n)


from sys import stdout, stdin
import io
import os
input = stdin.readline
for t in range(int(input())):
	(n, k) = map(int, input().split())
	m = k
	a = [[0 for i in range(n)] for j in range(n)]
	i = 0
	j = 0
	c = 0
	while k != 0:
		a[i][j] = 1
		k -= 1
		i += 1
		if i == n:
			i = 0
			j = c
			c += 1
		j = (j + 1) % n
	rmax = 0
	rmin = 400
	for i in range(n):
		z = sum(a[i])
		rmax = max(rmax, z)
		rmin = min(rmin, z)
	x = [0 for i in range(n)]
	for i in range(n):
		for j in range(n):
			x[j] += a[i][j]
	print(pow(rmax - rmin, 2) + pow(max(x) - min(x), 2))
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print('')


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	vals = []
	for i in range(n):
		vals += [((j + i) % n, j) for j in range(n)]
	res = [[0] * n for _ in range(n)]
	for (x, y) in vals[:k]:
		res[y][x] = 1
	print(0 if k % n == 0 else 2)
	for row in res:
		print(*row, sep='')


t = int(input())
for test in range(t):
	(n, k) = [int(i) for i in input().split()]
	tab = [['0' for c in range(n)] for r in range(n)]
	row = 0
	col = 0
	while k > 0:
		tab[row][col] = '1'
		row = (row + 1) % n
		col += 1
		if col == n:
			col = 0
			row = (row + 1) % n
		k -= 1
	if col == 0:
		print(0)
	else:
		print(2)
	for row in range(n):
		print(''.join(tab[row]))


import os
write = os.sys.stdout.write
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	a = [[0 for i in range(n)] for j in range(n)]
	if k % n == 0:
		write('0\n')
	else:
		write('2\n')
	(p1, p2) = (0, 0)
	while k > 0:
		a[p1][p2] = 1
		k -= 1
		if p1 == n - 1:
			p1 = -1
			p2 += 1
		p1 += 1
		p2 += 1
		p2 %= n
	for i in range(n):
		write(''.join(map(str, a[i])) + '\n')


from collections import defaultdict as dd
from collections import deque
import bisect
import heapq

def ri():
	return int(input())

def rl():
	return list(map(int, input().split()))

def solve():
	(n, k) = rl()
	(l, num_hi) = divmod(k, n)
	h = l + 1
	num_lo = n - num_hi
	A = []
	for i in range(n):
		A.append(['0'] * n)
	ptr = 0
	for row in range(num_hi):
		for _ in range(h):
			A[row][ptr] = '1'
			ptr = (1 + ptr) % n
	for row in range(num_hi, n):
		for _ in range(l):
			A[row][ptr] = '1'
			ptr = (1 + ptr) % n
	if num_hi == 0:
		print(0)
	else:
		print(2)
	for row in range(n):
		print(''.join(A[row]))
mode = 'T'
if mode == 'T':
	t = ri()
	for i in range(t):
		solve()
else:
	solve()


for i in range(int(input())):
	(n, k) = (int(i) for i in input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	g = k // n
	N = [['0'] * n for i in range(n)]
	for i in range(g):
		for j in range(n):
			N[(j + i) % n][j % n] = '1'
	if k % n != 0:
		for j in range(k % n):
			N[(j + g) % n][j % n] = '1'
	for i in range(n):
		print(''.join(N[i]))


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
for t in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n:
		print(2)
	else:
		print(0)
	a = [[0 for i in range(n)] for j in range(n)]
	i = 0
	j = 0
	c = 0
	while k != 0:
		a[i][j] = 1
		k -= 1
		i += 1
		if i == n:
			i = 0
			j = c
			c += 1
		j = (j + 1) % n
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print('')


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split(' '))
	mat = [[0 for i in range(n)] for j in range(n)]
	x = k // n
	y = k % n
	if y != 0:
		ans = 2
	else:
		ans = 0
	r = 0
	for i in range(n):
		if i + x < n:
			for j in range(i, i + x):
				mat[r][j] = 1
		else:
			for j in range(i, n):
				mat[r][j] = 1
			for j in range(x - n + i):
				mat[r][j] = 1
		r += 1
	r = 0
	for i in range(1, y + 1):
		mat[i][i - 1] = 1
	print(ans)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print()


TC = int(input())
while TC:
	(n, k) = list(map(int, input().split()))
	ans = [[0 for i in range(n)] for j in range(n)]
	nextRow = 1
	nextCol = 1
	r = 0
	c = 0
	up = True
	if k % n == 0:
		print(0)
	else:
		print(2)
	first = True
	while k:
		ans[r][c] = 1
		r += 1
		c += 1
		if c == n and up:
			r = 0
			c = nextCol
			nextCol += 1
			up = not up
		elif r == n and (not up):
			r = nextRow
			c = 0
			nextRow += 1
			up = not up
		else:
			r %= n
			c %= n
		k -= 1
	for i in range(n):
		for j in range(n):
			print(ans[i][j], end='')
		print()
	TC -= 1


for test_i in range(int(input())):
	(n, k) = map(int, input().split())
	if n * n == k:
		print(0)
		for i in range(n):
			print('1' * n)
	else:
		k0 = k // n
		dk = k % n
		print(2 if dk else 0)
		for i in range(k0 + 1):
			print(max(0, k0 - i) * '1' + (n - k0 - (1 if dk >= i + 1 else 0)) * '0' + (i + (1 if dk >= i + 1 else 0)) * '1')
		for i in range(k0 + 1, n):
			print((n - i - (1 if dk >= i + 1 else 0)) * '0' + (k0 + (1 if dk >= i + 1 else 0)) * '1' + (i - k0) * '0')


import sys
input = sys.stdin.readline
from collections import *
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = [[0] * n for _ in range(n)]
	for i in range(n):
		s = i
		for j in range(n):
			if k == 0:
				break
			a[j][s] = 1
			s += 1
			s %= n
			k -= 1
	(R, C) = ([], [])
	for i in range(n):
		r = 0
		for j in range(n):
			if a[i][j] == 1:
				r += 1
		R.append(r)
	for i in range(n):
		c = 0
		for j in range(n):
			if a[j][i] == 1:
				c += 1
		C.append(c)
	print((max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2)
	for ai in a:
		print(''.join(map(str, ai)))


cases = int(input())
for i in range(cases):
	l1 = input().split(' ')
	n = int(l1[0])
	k = int(l1[1])
	ans = 0
	arr = []
	if n ** 2 == k:
		ans = 0
		for j in range(n):
			same = []
			for k in range(n):
				same.append('1')
			arr.append(same)
		print(ans)
		for a in arr:
			print(''.join(a))
		continue
	for i in range(n):
		sub = []
		for j in range(n):
			sub.append('0')
		arr.append(sub)
	if k == 0:
		print(0)
		for a in arr:
			print(''.join(a))
		continue
	row = 0
	col = 0
	while k > 0:
		arr[row][col] = '1'
		row += 1
		col = (col + 1) % n
		if row == n:
			row = 0
			col = (col + 1) % n
		k -= 1
	if int(l1[1]) % n == 0:
		ans = 0
	else:
		ans = 2
	print(ans)
	for a in arr:
		print(''.join(a))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	board = [[0] * n for _ in range(n)]
	cnt = 0
	for i in range(n):
		for j in range(n):
			if cnt == k:
				break
			board[(j + i) % n][j] = 1
			cnt += 1
		if cnt == k:
			break
	if k % n == 0:
		print(0)
	else:
		maxs = (k + n - 1) // n
		mins = k // n
		print(2 * (maxs - mins) ** 2)
	for i in range(n):
		print(''.join(map(str, board[i])))


tt = int(input())
for loop in range(tt):
	(n, k) = map(int, input().split())
	lis = [[0] * n for i in range(n)]
	ns = 0
	for si in range(n):
		if ns == k:
			break
		for i in range(n):
			lis[(si + i) % n][i] = 1
			ns += 1
			if ns == k:
				break
		else:
			continue
		break
	R = []
	for i in range(n):
		now = 0
		for j in range(n):
			now += lis[i][j]
		R.append(now)
	C = []
	for i in range(n):
		now = 0
		for j in range(n):
			now += lis[j][i]
		C.append(now)
	print((max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2)
	for i in lis:
		print(''.join(map(str, i)))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k // n <= 0:
		num = [[0 for k in range(n)] for l in range(n)]
		p1 = k // n
		re = k % n
		ad = 1
		i1 = 0
		for i in range(n):
			if i1 >= n:
				i1 = 0
			st = i1
			if ad <= re:
				tp = p1 + 1
			else:
				tp = p1
			while tp > 0:
				if st >= n:
					st = 0
				num[i][st] = 1
				st += 1
				tp -= 1
			i1 += 1
			ad += 1
		lis = []
		for i in range(n):
			co = 0
			for j in range(n):
				if num[i][j] == 1:
					co += 1
			lis.append(co)
		mar = max(lis)
		mir = min(lis)
		sto = []
		for i in range(n):
			co = 0
			for j in range(n):
				if num[j][i] == 1:
					co += 1
			sto.append(co)
		mac = max(sto)
		mic = min(sto)
		print((mar - mir) ** 2 + (mac - mic) ** 2)
		for i in range(n):
			for j in range(n):
				print(num[i][j], end='')
			print()
	else:
		num = [[0 for k in range(n)] for l in range(n)]
		p1 = k // n
		re = k % n
		ad = 1
		i1 = 0
		for i in range(n):
			if i1 >= n:
				i1 = 0
			st = i1
			if ad <= re:
				tp = p1 + 1
			else:
				tp = p1
			while tp > 0:
				if st >= n:
					st = 0
				num[i][st] = 1
				st += 1
				tp -= 1
			i1 += 1
			ad += 1
		lis = []
		for i in range(n):
			co = 0
			for j in range(n):
				if num[i][j] == 1:
					co += 1
			lis.append(co)
		mar = max(lis)
		mir = min(lis)
		sto = []
		for i in range(n):
			co = 0
			for j in range(n):
				if num[j][i] == 1:
					co += 1
			sto.append(co)
		mac = max(sto)
		mic = min(sto)
		print((mar - mir) ** 2 + (mac - mic) ** 2)
		for i in range(n):
			for j in range(n):
				print(num[i][j], end='')
			print()


import sys
T = int(input())
for tmp in range(T):
	(n, k) = map(int, sys.stdin.readline().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	A = [[0 for i in range(n)] for j in range(n)]
	cnt = 0
	for i in range(n):
		for j in range(n):
			cnt += 1
			if cnt > k:
				break
			A[j][(i + j) % n] = 1
		if cnt > k:
			break
	for i in range(n):
		for j in range(n):
			print(A[i][j], end='')
		print()


T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	kai = k // n
	od = k % n
	if od == 0:
		print(0)
	else:
		print(2)
	ans = [[0] * 2 * n for _ in range(n)]
	for i in range(kai):
		for j in range(n):
			ans[j][i + j] = 1
	for i in range(od):
		ans[i][kai + i] = 1
	tans = [[0] * n for _ in range(n)]
	for i in range(n):
		for j in range(n):
			tans[i][j] = max(ans[i][j], ans[i][j + n])
	for i in tans:
		print(*i, sep='')


t = int(input())
for q in range(0, t):
	(n, k) = map(int, input().split())
	a = [[0 for i in range(n)] for j in range(n)]
	if k == 0:
		print(0)
		for i in range(0, n):
			print(*a[i], sep='')
	elif k < n:
		print(2)
		for i in range(0, k):
			a[i][i] = 1
		for i in range(0, n):
			print(*a[i], sep='')
	elif k == n:
		print(0)
		for i in range(0, n):
			a[i][i] = 1
		for i in range(0, n):
			print(*a[i], sep='')
	else:
		for i in range(0, n):
			a[i][i] = 1
		k -= n
		if k % n == 0:
			print(0)
			m = k // n
			for i in range(0, n):
				j = i + 1
				count = 0
				while count < m:
					if j == n:
						j = 0
					a[i][j] = 1
					count += 1
					j += 1
			for i in range(0, n):
				print(*a[i], sep='')
		else:
			print(2)
			m1 = k // n
			m2 = m1 + 1
			rem = k % n
			for i in range(0, n):
				j = i + 1
				count = 0
				if rem > 0:
					m = m2
					rem -= 1
				else:
					m = m1
				while count < m:
					if j == n:
						j = 0
					a[i][j] = 1
					count += 1
					j += 1
			for i in range(0, n):
				print(*a[i], sep='')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0 for i in range(n)] for i in range(n)]
	(i, j) = (0, 0)
	while k:
		k -= 1
		mat[i][j] = 1
		(i, j) = (i + 1, j + 1)
		if i == n:
			i = 0
			j += 1
		j %= n
	r = [0 for i in range(n)]
	c = [0 for i in range(n)]
	for i in range(n):
		for j in range(n):
			r[i] += mat[i][j]
			c[j] += mat[i][j]
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in mat:
		for j in i:
			print(j, end='')
		print('')


import sys
import math
input = sys.stdin.readline

def inp():
	return int(input())

def inara():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def twoD_ara(n, m):
	ara = []
	for i in range(n):
		ara.append([])
		for j in range(m):
			ara[i].append(0)
	return ara

def sq(x):
	return x * x
t = inp()
for _ in range(t):
	(n, k) = invr()
	ara = twoD_ara(n, n)
	move = []
	for i in range(n):
		move.append([0, i])
	for last in move:
		while last[0] < n and k:
			ara[last[0]][last[1]] = 1
			k -= 1
			last[0] += 1
			last[1] += 1
			if last[1] == n:
				last[1] -= n
	row = [0] * n
	col = [0] * n
	for i in range(n):
		for j in range(n):
			row[i] += ara[i][j]
			col[j] += ara[i][j]
	row.sort()
	col.sort()
	a = sq(row[0] - row[n - 1])
	b = sq(col[0] - col[n - 1])
	ans = a + b
	print(ans)
	for i in range(n):
		for j in range(n):
			print(ara[i][j], end='')
		print()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	k1 = k
	g = [['0'] * n for i in range(n)]
	l = [i for i in range(n)]
	i = 0
	while k > 0:
		g[i][l[i]] = '1'
		l[i] = (l[i] + 1) % n
		i = (i + 1) % n
		k -= 1
	if k1 % n == 0:
		print(0)
	else:
		print(2)
	for x in g:
		print(''.join(x))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	mat = [[0 for i in range(n)] for j in range(n)]
	d = {}
	ans = 0
	if k % n != 0 and n > 1:
		ans = 2
	for i in range(n):
		for j in range(n):
			if d.get(i - j):
				d[i - j].append([i, j])
			else:
				d[i - j] = [[i, j]]
	key = []
	for i in range(n):
		if i == 0:
			key.append(i)
		else:
			key.append(-i)
			key.append(n - i)
	for i in key:
		for j in d[i]:
			if k > 0:
				mat[j[0]][j[1]] = '1'
				k -= 1
			else:
				mat[j[0]][j[1]] = '0'
	print(ans)
	for i in mat:
		print(''.join(i))


t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	m = [[0] * n for _ in range(n)]
	for i in range(k // n + 1):
		if k - i * n >= n:
			x = n
		else:
			x = k % n
		for j in range(x):
			m[(i + j) % n][j % n] = 1
	(l, c) = ([0] * n, [0] * n)
	for i in range(n):
		for j in range(n):
			l[i] += m[i][j]
			c[j] += m[i][j]
	print((max(l) - min(l)) ** 2 + (max(c) - min(c)) ** 2)
	for x in m:
		for y in x:
			print(y, end='')
		print()


from collections import deque
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from bisect import bisect_left as bl
from math import log2, ceil
from itertools import permutations

def main():
	for t in range(int(input())):
		(n, k) = [int(j) for j in input().split()]
		dr = [0 for i in range(n)]
		dc = [0 for i in range(n)]
		if k != 0:
			mn = k // n
			mod = k % n
		else:
			mn = 0
			mod = 0
		ans = [['0'] * n for i in range(n)]
		ct = 0
		i = 0
		j = 0
		while ct < k:
			ans[i][j] = '1'
			dr[i] += 1
			dc[j] += 1
			i += 1
			j += 1
			j = j % n
			i = i % n
			if i == 0:
				j += 1
				j = j % n
			ct += 1
		print((max(dr) - min(dr)) ** 2 + (max(dc) - min(dc)) ** 2)
		for i in range(n):
			print(''.join(map(str, ans[i])))
main()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	l = []
	for j in range(n):
		l.append([0] * n)
	v = 0
	while k > 0 and v < n:
		l[v][v] = 1
		k -= 1
		v += 1
	for j in range(1, n):
		for j1 in range(n - j):
			if k > 0:
				l[j1][j + j1] = 1
				k -= 1
		for j1 in range(j):
			if k > 0:
				l[n - j + j1][j1] = 1
				k -= 1
	maximum_r = 0
	minimum_r = 301
	for j in range(n):
		maximum_r = max(maximum_r, sum(l[j]))
		minimum_r = min(minimum_r, sum(l[j]))
	maximum_c = 0
	minimum_c = 301
	for j in range(n):
		s = 0
		for j1 in range(n):
			s += l[j1][j]
		maximum_c = max(maximum_c, s)
		minimum_c = min(minimum_c, s)
	print((maximum_r - minimum_r) ** 2 + (maximum_c - minimum_c) ** 2)
	for j in range(n):
		s = ''
		for k in range(n):
			s += str(l[j][k])
		print(s)


from sys import stdin
from math import ceil
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	(n, k) = [int(x) for x in inp().split()]
	ans = [[0] * n for i in range(n)]
	i = 0
	j = 0
	nextDown = [n - 1, 0]
	nextUp = [0, 1]
	flag = True
	for x in range(k):
		ans[i][j] = 1
		i += 1
		j += 1
		if i > n - 1 or j > n - 1:
			if flag:
				(i, j) = nextDown
				nextDown[0] -= 1
			else:
				(i, j) = nextUp
				nextUp[1] += 1
			flag = not flag
	if k % n:
		print(2)
	else:
		print(0)
	for i in range(n):
		print(''.join(map(str, ans[i])))


from math import gcd
import sys

def inp():
	return sys.stdin.readline().strip()
t = int(inp())
for _ in range(t):
	(n, k) = map(int, inp().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	A = [['0'] * n for _ in range(n)]
	i = 0
	j = 0
	while k > 0:
		A[i][j] = '1'
		k = k - 1
		i = (i + 1) % n
		j = (j + 1) % n
		if i == 0:
			i = 0
			j = (j + 1) % n
	for i in A:
		print(''.join(i))


import sys
import copy
import math

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
t = int(input())
for test in range(t):
	(n, k) = map(int, input().split())
	arr = [[0 for i in range(n)] for i in range(n)]
	ok = True
	for i in range(n):
		for j in range(n):
			if k == 0:
				ok = False
				break
			arr[j % n][(i + j) % n] = 1
			k -= 1
		if ok == False:
			break
	ans = []
	mnr = n
	mxr = 0
	for i in range(n):
		s = ''
		temp = 0
		for j in range(n):
			temp += arr[i][j]
			s += str(arr[i][j])
		ans.append(s)
		mnr = min(mnr, temp)
		mxr = max(mxr, temp)
	mnc = n
	mxc = 0
	for i in range(n):
		temp = 0
		for j in range(n):
			if arr[j][i] == 1:
				temp += 1
		mnc = min(mnc, temp)
		mxc = max(mxc, temp)
	print((mnc - mxc) ** 2 + (mxr - mnr) ** 2)
	for i in range(n):
		print(ans[i])


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	matrix = [[0 for i in range(n)] for j in range(n)]
	cnt = k // n
	for i in range(n):
		for j in range(cnt):
			matrix[i][(i + j) % n] = 1
	did = 0
	ost = k % n
	for i in range(n):
		if did == ost:
			break
		for j in range(n):
			if did == ost:
				break
			if i - j == 1 and matrix[i][j] == 0:
				matrix[i][j] = 1
				did += 1
	for i in range(n):
		for j in range(n):
			print(matrix[i][j], end='')
		print()


import sys
from collections import deque, defaultdict
from itertools import product
input = sys.stdin.buffer.readline
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	bd = [[0] * n for _ in range(n)]
	p = 0
	for r in range(n):
		cc = k // n + (1 if r < k % n else 0)
		for c in range(cc):
			bd[r][p % n] = 1
			p += 1
	print(2 if k % n else 0)
	for ls in bd:
		print(''.join(map(str, ls)))


t = int(input())
for x in range(t):
	(n, k) = map(int, input().split(' '))
	c = k // n
	if k % n == 0:
		print(0)
		for i in range(n):
			a = [0 for i in range(n)]
			for j in range(c):
				a[(i + j) % n] = 1
			print(''.join((str(q) for q in a)))
	else:
		print(2)
		rem = k - c * n
		for i in range(n):
			a = [0 for i in range(n)]
			b = c
			if rem > 0:
				b += 1
			for j in range(b):
				a[(i + j) % n] = 1
			rem -= 1
			print(''.join((str(q) for q in a)))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from math import sqrt, floor, factorial, gcd, log, ceil
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from math import gcd
from bisect import bisect

def solution():
	for i in range(int(input())):
		(n, k) = map(int, input().split())
		a = [0] * n
		for i in range(0, n):
			a[i] = k // n
		for i in range(0, k % n):
			a[i] += 1
		f = 2 * (max(a) - min(a)) ** 2
		print(f)
		o = [[0 for j in range(n)] for i in range(n)]
		for i in range(n):
			for j in range(n):
				if k <= 0:
					break
				else:
					o[j][(j + i) % n] = 1
					k -= 1
		for i in range(n):
			for j in range(n):
				print(o[i][j], end='')
			print()
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
read = lambda : list(map(int, input().strip().split(' ')))
solution()


def print_matrix(n, k):
	(row, col) = (0, 0)
	matrix = [['0' for i in range(n)] for j in range(n)]
	for i in range(k):
		matrix[row][col] = '1'
		row += 1
		col = (col + 1) % n
		if row == n:
			row = 0
			col = (col + 1) % n
	if n * (k // n) == k:
		print('0')
	else:
		print('2')
	print('\n'.join([''.join(a) for a in matrix]))
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	print_matrix(n, k)


for qq in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0] * n for i in range(n)]
	b = 0
	try:
		while k:
			for i in range(n):
				a[(b + i) % n][i % n] = 1
				k -= 1
				if k == 0:
					raise
			b += 1
	except:
		pass
	(maxR, minR) = (0, n)
	for i in range(n):
		x = 0
		for j in range(n):
			x += a[i][j]
		maxR = max(maxR, x)
		minR = min(minR, x)
	(maxC, minC) = (0, n)
	for j in range(n):
		x = 0
		for i in range(n):
			x += a[i][j]
		maxC = max(maxC, x)
		minC = min(minC, x)
	print((maxR - minR) ** 2 + (maxC - minC) ** 2)
	for v in a:
		print(*v, sep='')


def pr(l):
	maxi = 0
	mini = len(l) + 69
	maxj = 0
	minj = len(l) + 69
	for i in range(len(l)):
		temp = sum(l[i])
		if temp > maxi:
			maxi = temp
		if temp < mini:
			mini = temp
	for j in range(len(l)):
		temp = 0
		for i in range(len(l)):
			temp += l[i][j]
		if temp > maxj:
			maxj = temp
		if temp < minj:
			minj = temp
	print((maxi - mini) ** 2 + (maxj - minj) ** 2)
	for i in range(len(l)):
		print(''.join(map(str, l[i])))
t = int(input())
for q in range(t):
	(n, k) = map(int, input().split())
	l = []
	w = str(k)
	w = int(w)
	for i in range(n):
		l.append([0] * n)
	for i in range(min(n, w)):
		l[i][i] = 1
	w -= n
	if w <= 0:
		pr(l)
		continue
	i = 1
	j = 0
	nd = 1
	for e in range(w):
		l[i][j] = 1
		i += 1
		j += 1
		if i >= n:
			i = 0
		if j >= n:
			j = 0
			nd += 1
			i = nd
	pr(l)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	A = []
	for i in range(n):
		a = [0] * n
		A.append(a)
	if k % n == 0:
		print(0)
	else:
		print(2)
	p = 0
	q = 0
	for i in range(0, k):
		A[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	for i in range(n):
		for j in range(n):
			print(A[i][j], end='')
		print()


def solve():
	(n, m) = map(int, input().split())
	ans = 2 if m % n else 0
	a = [[0] * n for _ in range(n)]
	for i in range(n):
		if m <= 0:
			break
		for j in range(n):
			if m <= 0:
				break
			a[j][(i + j) % n] = 1
			m -= 1
	print(ans)
	for i in a:
		print(*i, sep='')
t = int(input())
for _ in range(t):
	solve()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	matrix = [[0 for i in range(n)] for j in range(n)]
	pos = [0, 0]
	cur = 0
	for i in range(k // n + (k % n != 0)):
		for j in range(n):
			if cur == k:
				break
			matrix[pos[0] % n][pos[1] % n] = 1
			pos[0] += 1
			pos[1] += 1
			cur += 1
		pos[0] += 1
	r = [0] * n
	c = [0] * n
	for i in range(n):
		for j in range(n):
			r[i] += matrix[i][j]
			c[j] += matrix[i][j]
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	[print(''.join([str(j) for j in i])) for i in matrix]


def ans(N, K):
	mat = []
	for _ in range(N):
		row = [0] * N
		mat += [row]
	offset = 0
	x = 0
	y = 0
	for i in range(K):
		mat[x][y] = 1
		x += 1
		y += 1
		x = x % N
		y = y % N
		if x == 0:
			y += 1
			assert y <= N
	R = []
	for i in range(N):
		R += [sum(mat[i])]
	mat = list(zip(*mat))
	C = []
	for i in range(N):
		C += [sum(mat[i])]
	print((max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2)
	for row in mat:
		print(''.join(map(str, row)))
T = int(input())
for _ in range(T):
	(n, k) = input().split(' ')
	n = int(n)
	k = int(k)
	ans(n, k)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, k):
	a = [[0] * n for _ in range(n)]
	cnt = min(k, n)
	for i in range(cnt):
		a[i][i] = 1
	if k > cnt:
		dr = 1
		for d in range(1, 2 * n):
			done = False
			if dr == 1:
				dn = n - (d + 1) // 2
				for r in range(dn):
					a[r][r + (d + 1) // 2] = 1
					cnt += 1
					if cnt == k:
						done = True
						break
				dr = -1
			else:
				for r in range(d // 2):
					a[n - d // 2 + r][r] = 1
					cnt += 1
					if cnt == k:
						done = True
						break
				dr = 1
			if done:
				break
	rr = [sum(a[i]) for i in range(n)]
	r_min = min(rr)
	r_max = max(rr)
	cc = [0] * n
	for r in range(n):
		for j in range(n):
			cc[j] += a[r][j]
	c_min = min(cc)
	c_max = max(cc)
	f = (r_max - r_min) ** 2 + (c_max - c_min) ** 2
	wi(f)
	for i in range(n):
		ws(''.join([str(x) for x in a[i]]))

def main():
	for _ in range(ri()):
		(n, k) = ria()
		solve(n, k)

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	ptr = [i for i in range(n)]
	mat = [[0 for i in range(n)] for j in range(n)]
	p = 0
	row = 0
	for i in range(k):
		mat[row][ptr[p]] = 1
		ptr[p] = (ptr[p] + 1) % n
		p = (p + 1) % n
		row = (row + 1) % n
	r = [0 for i in range(n)]
	c = [0 for i in range(n)]
	for i in range(n):
		cnt = 0
		for j in range(n):
			cnt += mat[i][j]
		r[i] = cnt
	for i in range(n):
		cnt = 0
		for j in range(n):
			cnt += mat[j][i]
		c[i] = cnt
	t1 = (max(r) - min(r)) ** 2
	t2 = (max(c) - min(c)) ** 2
	ans = t1 + t2
	print(ans)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print()


inp = lambda : int(input())
inpm = lambda : map(int, input().split())
inpl = lambda : list(inpm())
l2mn = lambda _n, _m: [[0 for __ in range(_m)] for _ in range(_n)]
l2n = lambda _n: l2mn(_n, _n)
INF = int(1e+18)
MOD = int(1000000000.0) + 7
N = 2000009

def pr(a):
	for s in a:
		print(*s, sep='')

def ss(a):
	s = 0
	for e in a:
		s += sum(e)
	return s
A = [[1, 1, 1], [1, 1, 1], [1, 0, 1]]

def solve():
	(n, k) = inpm()
	if n == 3 and k == 8:
		print(2)
		pr(A)
		return
	kk = k % n
	res = 0 if kk == 0 else 2
	a = [[0 for j in range(n)] for i in range(n)]
	if k == 0:
		print(res)
		pr(a)
		return
	b = False
	for q in range(0, n, 2):
		for i in range(n - q):
			a[i + q][i] = 1
			k -= 1
			if k == 0:
				b = True
				break
		if b:
			break
		for i in range(q):
			a[i][n - q + i] = 1
			k -= 1
			if k == 0:
				b = True
				break
		if b:
			break
	if k == 0:
		print(res)
		pr(a)
		return
	for q in range(1, n, 2):
		for i in range(n - q):
			a[i + q][i] = 1
			k -= 1
			if k == 0:
				b = True
				break
		if b:
			break
		for i in range(q):
			a[i][n - q + i] = 1
			k -= 1
			if k == 0:
				b = True
				break
		if b:
			break
	print(res)
	pr(a)

def main():
	t = inp()
	for i in range(t):
		solve()
main()


def smallest(a, k):
	mylist = []
	for x in range(len(a)):
		mylist.append((a[x], x))
	mylist = sorted(mylist)
	mylist2 = []
	for x in range(k):
		mylist2.append(mylist[x][1])
	return mylist2
from sys import stdin, stdout
for query in range(int(stdin.readline())):
	nk = stdin.readline().split()
	n = int(nk[0])
	k = int(nk[1])
	nums = [k // n] * n
	for x in range(k - k // n * n):
		nums[x] += 1
	rowsums = [0] * n
	ans = [[0] * n for x in range(n)]
	for x in range(n):
		for y in smallest(rowsums, nums[x]):
			ans[y][x] = 1
			rowsums[y] += 1
	stdout.write(str((max(nums) - min(nums)) ** 2 * 2) + '\n')
	for x in ans:
		for y in x:
			stdout.write(str(y))
		stdout.write('\n')


import math
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	matrix = [[0 for i in range(n)] for j in range(n)]
	cnt = 0
	diff = 0
	while cnt < k:
		for i in range(n):
			matrix[i][(i + diff) % n] = 1
			cnt += 1
			if cnt == k:
				break
		if cnt == k:
			break
		diff += 1
	(row_min_cnt, row_max_cnt) = (float('inf'), 0)
	for i in range(n):
		row_min_cnt = min(row_min_cnt, sum(matrix[i][:]))
		row_max_cnt = max(row_max_cnt, sum(matrix[i][:]))
	(col_min_cnt, col_max_cnt) = (float('inf'), 0)
	for i in range(n):
		col_min_cnt = min(col_min_cnt, sum(matrix[:][i]))
		col_max_cnt = max(col_max_cnt, sum(matrix[:][i]))
	func = math.pow(abs(row_max_cnt - row_min_cnt), 2) + math.pow(abs(col_max_cnt - col_min_cnt), 2)
	print(int(func))
	for i in range(n):
		ans = ''
		for j in range(n):
			ans += str(matrix[i][j])
		print(ans)


import sys
import math
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
t = int(input())
for case in range(t):
	(n, k) = map(int, input().split())
	plus = 0
	if k % n == 0:
		print(0)
	else:
		print(2)
		plus = k % n
	lim = k // n
	start = 0
	for i in range(n):
		lis = ['0'] * n
		if i < plus:
			tmp = lim + 1
		else:
			tmp = lim
		for j in range(tmp):
			lis[(start + j) % n] = '1'
		start += tmp
		print(''.join(lis))


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, K):
	grid = [[0 for i in range(N)] for j in range(N)]
	if K != 0:
		for d in range(2 * N):
			for r in range(N):
				c = d + r
				if K:
					grid[r][c % N] = 1
					K -= 1
	rowMin = float('inf')
	rowMax = float('-inf')
	colMin = float('inf')
	colMax = float('-inf')
	ans = []
	for i in range(N):
		rowMin = min(rowMin, sum((grid[i][j] for j in range(N))))
		rowMax = max(rowMax, sum((grid[i][j] for j in range(N))))
		colMin = min(colMin, sum((grid[j][i] for j in range(N))))
		colMax = max(colMax, sum((grid[j][i] for j in range(N))))
		ans.append(''.join(map(str, grid[i])))
	return str((rowMax - rowMin) ** 2 + (colMax - colMin) ** 2) + '\n' + '\n'.join(ans)
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N, K) = [int(x) for x in input().split()]
	ans = solve(N, K)
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = [[0 for i in range(n)] for j in range(n)]
	m = k // n
	i1 = 0
	j1 = 0
	while i1 < m and j1 < m:
		arr[i1][j1] = 1
		if i1 == 0:
			i1 = j1 + 1
			j1 = 0
		else:
			i1 -= 1
			j1 += 1
	for j in range(n - m, n):
		x = j
		y = n - 1
		while x < n:
			arr[y][x] = 1
			x += 1
			y -= 1
	y_in = 1
	for i in range(m, n):
		x_in = i
		y1 = y_in
		ck = 0
		while ck < m and y1 < n:
			arr[x_in][y1] = 1
			ck += 1
			x_in -= 1
			y1 += 1
		y_in += 1
	final = k % n
	if m % 2 == 0:
		if n % 2 == 0:
			x = n - 2
			y = 0
			while final > 0:
				arr[x][y] = 1
				x -= 1
				y += 1
				final -= 1
		else:
			x = n - 1
			y = 0
			while final > 0:
				arr[x][y] = 1
				x -= 1
				y += 1
				final -= 1
	elif n % 2 != 0:
		x = n - 2
		y = 0
		while final > 0:
			arr[x][y] = 1
			x -= 1
			y += 1
			final -= 1
	else:
		x = n - 1
		y = 0
		while final > 0:
			arr[x][y] = 1
			x -= 1
			y += 1
			final -= 1
	cost = 0
	mnm1 = 1e+18
	mxm1 = 0
	for i in range(0, n):
		sum = 0
		for j in range(0, n):
			sum += arr[i][j]
		mxm1 = max(mxm1, sum)
		mnm1 = min(mnm1, sum)
	cost = abs(mxm1 - mnm1) ** 2
	mnm1 = 1e+18
	mxm1 = 0
	for i in range(0, n):
		sum = 0
		for j in range(0, n):
			sum += arr[j][i]
		mxm1 = max(mxm1, sum)
		mnm1 = min(mnm1, sum)
	cost += abs(mxm1 - mnm1) ** 2
	print(int(cost))
	for i in range(n):
		for j in range(n):
			print(arr[i][j], end='')
		print('')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0] * n for w in range(n)]
	(p, q) = (0, 0)
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(k):
		a[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	for e in a:
		print(''.join((str(e1) for e1 in e)))


from heapq import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = [['0' for _ in range(n)] for _ in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	i = 0
	j = 0
	for x in range(k):
		ans[i][j] = '1'
		i += 1
		j += 1
		j %= n
		if i == n:
			i = 0
			j += 1
			j %= n
	for i in ans:
		print(''.join(i))


import sys
import heapq
import random
import collections
import bisect

def solve(n, k):
	cnt = 0
	grid = [[0 for _ in range(n)] for _ in range(n)]
	for i in range(n):
		for j in range(n):
			if cnt == k:
				break
			grid[j % n][(i + j) % n] = 1
			cnt += 1
	max_row = 0
	max_col = 0
	min_row = n
	min_col = n
	for row in grid:
		sum_row = sum(row)
		max_row = max(max_row, sum_row)
		min_row = min(min_row, sum_row)
	for row in zip(*grid):
		sum_row = sum(row)
		max_col = max(max_col, sum_row)
		min_col = min(min_col, sum_row)
	print((max_col - min_col) ** 2 + (max_col - min_col) ** 2)
	return grid

def console(*args):
	print('\x1b[36m', *args, '\x1b[0m', file=sys.stderr)
	return
for case_num in range(int(input())):
	(n, k) = list(map(int, input().split()))
	res = solve(n, k)
	for row in res:
		print(''.join([str(x) for x in row]))


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def Yes(c):
	return IF(c, 'Yes', 'No')

def main():
	t = I()
	rr = []
	for _ in range(t):
		(n, k) = LI()
		rr.append(IF(k % n == 0, 0, 2))
		r = [[0] * n for _ in range(n)]
		for i in range(n):
			if k < 1:
				break
			for j in range(n):
				if k < 1:
					break
				r[i - j][j] = 1
				k -= 1
		rr.append(JAA(r, '\n', ''))
	return JA(rr, '\n')
print(main())


for t in range(int(input())):
	(n, k) = map(int, input().split())
	arr = [['0' for i in range(n)] for j in range(n)]
	p = q = 0
	for i in range(k):
		arr[p][q] = '1'
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	print(0 if k % n == 0 else 2)
	for i in range(n):
		print(''.join(arr[i]))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = [[0 for i in range(n)] for j in range(n)]
	r = 0
	c = 0
	for i in range(k):
		arr[r][c] = 1
		r += 1
		c += 1
		c %= n
		if r == n:
			r = 0
			c += 1
			c = c % n
	print(0) if k % n == 0 else print(2)
	for j in arr:
		print(''.join((str(i) for i in j)))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	board = [[0] * n for i in range(n)]
	if k == 0:
		print(0)
		for i in board:
			print(''.join(map(str, i)))
	else:
		for i in range(n):
			if k > 0:
				board[i][i] = 1
				k -= 1
		alt = 1
		while k > 0:
			for i in range(n):
				if k > 0:
					board[(i + alt) % n][i] = 1
					k -= 1
			alt += 1
		mx = sum(board[0])
		mn = sum(board[0])
		for i in range(n):
			sm = sum(board[i])
			mx = max(mx, sm)
			mn = min(mn, sm)
		score = (mx - mn) ** 2
		mx = 0
		mn = 1e+18
		for j in range(n):
			sm = 0
			for i in range(n):
				sm += board[i][j]
			mx = max(mx, sm)
			mn = min(mn, sm)
		score += (mx - mn) ** 2
		print(score)
		for i in board:
			print(''.join(map(str, i)))


import math, bisect, collections, itertools, datetime, functools, sys, os
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
for testcase in range(int(input())):
	(n, k) = map(int, input().split())
	dp = [[0 for i in range(n)] for j in range(n)]
	for i in range(n):
		for j in range(n):
			if k:
				dp[j][(j + i) % n] = 1
				k -= 1
	row = [0 for i in range(n)]
	col = [0 for i in range(n)]
	for i in range(n):
		for j in range(n):
			if dp[i][j] == 1:
				row[i] += 1
				col[j] += 1
	max_row = max(row)
	max_col = max(col)
	min_col = min(col)
	min_row = min(row)
	ans = (max_row - min_row) ** 2 + (max_col - min_col) ** 2
	print(ans)
	for i in range(n):
		for j in range(n):
			print(dp[i][j], end='')
		print()


import sys
input = sys.stdin.readline

def getInt():
	return int(input())

def getVars():
	return map(int, input().split())

def getList():
	return list(map(int, input().split()))

def getStr():
	return input().strip()
t = getInt()
for _ in range(t):
	(n, k) = getVars()
	res = ['0' * n] * n
	p = k // n
	m = k % n
	if m == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		k1 = p
		if m > 0:
			k1 += 1
			m -= 1
		a = [0, min(i, n - k1), k1, 0]
		a[3] = n - a[0] - a[1] - a[2]
		if i > a[1]:
			a[0] = i + a[2] - n
			a[2] -= a[0]
		s = '1' * a[0] + '0' * a[1] + '1' * a[2] + '0' * a[3]
		print(s)


for i in range(int(input())):
	(n, k) = [int(x) for x in input().split()]
	if k % n == 0:
		print(0)
	else:
		print(2)
	res = [[0 for i in range(n)] for j in range(n)]
	(p, q) = (0, 0)
	while k > 0:
		res[p][q] = 1
		p += 1
		q += 1
		q %= n
		if p == n:
			p = 0
			q += 1
			q %= n
		k -= 1
	for i in res:
		print(*i, sep='')


for _ in range(int(input())):
	(n, k) = [int(c) for c in input().split()]
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	mat = [[0 for i in range(n)] for i in range(n)]
	p = 0
	q = 0
	while k:
		mat[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q += 1
			q % n
		k -= 1
	print(ans)
	for i in mat:
		print(*i, sep='')


import sys
input = sys.stdin.readline
ans1 = []
ans2 = []
for i in range(int(input())):
	(n, k) = map(int, input().split())
	b = []
	x = k // n
	y = k % n
	for j in range(n):
		if y > 0:
			b.append(x + 1)
			y -= 1
		else:
			b.append(x)
	A = [[0 for i in range(n)] for j in range(n)]
	x = 0
	for i in range(n):
		for j in range(x, x + b[x]):
			A[i][j % n] = 1
		x += 1
	if b[0] == b[-1]:
		ans1.append(0)
	else:
		ans1.append(2)
	ans2.append(A)
for i in range(len(ans1)):
	print(ans1[i])
	for j in ans2[i]:
		print(*j, sep='')


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	grid = [[1 for x in range(n)] for y in range(n)]
	s = n * n
	i = 0
	j = 0
	i_s = 0
	j_s = 0
	while s > k:
		grid[i][j] = 0
		s -= 1
		if i == n - 1:
			j_s += 1
			(i, j) = (i_s, j_s)
		else:
			i += 1
			j += 1
			j %= n
	(max_r, min_r, max_c, min_c) = (0, n, 0, n)
	for i in range(n):
		r = 0
		c = 0
		for j in range(n):
			r += grid[i][j]
			c += grid[j][i]
		max_r = max(r, max_r)
		min_r = min(r, min_r)
		max_c = max(c, max_c)
		min_c = min(c, min_c)
	print((max_r - min_r) ** 2 + (max_c - min_c) ** 2)
	print('\n'.join([''.join([str(x) for x in row]) for row in grid]))


import sys
import math
import collections
import heapq

def set_debug(debug_mode=False):
	if debug_mode:
		fin = open('input.txt', 'r')
		sys.stdin = fin

def int_input():
	return list(map(int, input().split()))

def get(s):
	return str(s % 9) + '9' * (s // 9)
t = int(input())
for ti in range(1, t + 1):
	(n, k) = int_input()
	res = [[0] * n for _ in range(n)]
	for i in range(n):
		if k == 0:
			break
		r = 0
		c = i
		for j in range(n):
			res[r][c] = 1
			r = (r + 1) % n
			c = (c + 1) % n
			k -= 1
			if k == 0:
				break
	row = [0] * n
	col = [0] * n
	for i in range(n):
		for j in range(n):
			if res[i][j]:
				row[i] += 1
				col[i] += 1
	print((max(row) - min(row)) ** 2 + (max(col) - min(col)) ** 2)
	for s in res:
		print(''.join([str(x) for x in s]))


t = int(input())
for i in range(t):
	nk = list(map(int, input().split()))
	n = nk[0]
	k = nk[1]
	arr = [['0'] * n for i in range(n)]
	p = 0
	q = 0
	for f in range(k):
		arr[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for j in arr:
		print(*j, sep='')


from sys import stdin, stdout
stdin.readline

def mp():
	return list(map(int, stdin.readline().strip().split()))

def it():
	return int(stdin.readline().strip())
from collections import defaultdict as dd, Counter as C, deque
from math import ceil, gcd

def fun(n, x):
	v = [['0' for _ in range(n)] for _ in range(n)]
	(j, k) = (0, 0)
	for i in range(x):
		v[j][k] = '1'
		j += 1
		k = (k + 1) % n
		if j == n:
			j = 0
			k = (k + 1) % n
	for t in range(n):
		print(''.join(v[t]))
for _ in range(it()):
	(n, k) = mp()
	if k % n:
		print(2)
	else:
		print(0)
	fun(n, k)


from sys import stdin, stdout, setrecursionlimit
from math import gcd, ceil, sqrt
from collections import Counter, deque
from bisect import bisect_left, bisect_right
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
setrecursionlimit(100000)
mod = 1000000007
tc = ii1()
for _ in range(tc):
	(n, k) = iia()
	arr = []
	for i in range(n):
		arr.append(['0'] * n)
	a = b = 0
	for i in range(k):
		arr[a][b] = '1'
		a += 1
		b = (b + 1) % n
		if a == n:
			a = 0
			b = (b + 1) % n
	(t1, t2) = ([], [])
	for i in arr:
		t1.append(i.count('1'))
	for i in range(n):
		cur = 0
		for j in range(n):
			if arr[j][i] == '1':
				cur += 1
		t2.append(cur)
	(t1, t2) = (sorted(t1), sorted(t2))
	print(pow(t1[-1] - t1[0], 2) + pow(t2[-1] - t2[0], 2))
	for i in arr:
		print(*i, sep='')


import sys
input = lambda : sys.stdin.readline().strip()
t = int(input())
while t:
	t -= 1
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	ans = [[0] * n for _ in range(n)]
	p = 0
	q = 0
	while k:
		ans[p][q] = 1
		k -= 1
		p += 1
		q += 1
		q %= n
		if p == n:
			p = 0
			q += 1
			q %= n
	for i in range(n):
		print(''.join(map(str, ans[i])))


from sys import stdin
import math

def inp():
	return stdin.readline().strip()
t = int(inp())
for _ in range(t):
	(n, k) = [int(x) for x in inp().split()]
	ar = [[0] * n for i in range(n)]
	first = [0] * n
	for i in range(n):
		first[i] += i
	for i in range(k):
		ar[i % n][first[i % n]] = 1
		if i % n == 0:
			first[i % n] += 1
		else:
			first[i % n] = (first[i % n - 1] + 1) % n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(map(str, ar[i])))


T = int(input())
for _ in range(T):
	(n, k) = [int(_) for _ in input().split()]
	x = y = 0
	g = [[0 for _ in range(n)] for _ in range(n)]
	for _ in range(k):
		g[x][y] = 1
		(x, y) = (x + 1, (y + 1) % n)
		if x == n:
			(x, y) = (0, (y + 1) % n)
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		for j in range(n):
			print(g[i][j], end='')
		print()


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	(N, K) = MAP()
	grid = list2d(N, N, 0)
	cnt = K
	for i in range(N):
		if not cnt:
			break
		for j in range(N):
			if not cnt:
				break
			grid[j][(j + i) % N] = 1
			cnt -= 1
	mnh = mnw = INF
	mxh = mxw = 0
	for i in range(N):
		mnw = min(mnw, grid[i].count(1))
		mxw = max(mxw, grid[i].count(1))
	grid = list(zip(*grid))
	for i in range(N):
		mnh = min(mnh, grid[i].count(1))
		mxh = max(mxh, grid[i].count(1))
	ans = mxh - mnh + (mxw - mnw)
	print(ans)
	grid = list(zip(*grid))
	for i in range(N):
		print(''.join(map(str, grid[i])))


for _ in range(int(input())):
	(n, k) = map(int, input().strip().split())
	print(2 if k % n else 0)
	ans = [[0] * n for _ in range(n)]
	I = 0
	while k:
		c = min(k, n)
		k -= c
		(i, j) = (I, 0)
		while c and i < n:
			ans[i][j] = 1
			i += 1
			j += 1
			c -= 1
		(i, j) = (0, n - I)
		while c:
			ans[i][j] = 1
			i += 1
			j += 1
			c -= 1
		I += 1
	for i in range(n):
		for j in range(n):
			print(ans[i][j], end='')
		print()


inp = lambda : map(int, input().split(' '))
(t,) = inp()
for _ in range(t):
	(n, k) = inp()
	arr = [['0'] * n for i in range(n)]
	it = 0
	print(2 * (k % n != 0))
	while True:
		if k == 0:
			break
		for row in range(n):
			if k == 0:
				break
			arr[row][(row + it) % n] = '1'
			k -= 1
		it += 1
	for i in range(n):
		print(''.join(arr[i]))


for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	res = 0 if k % n == 0 else 2
	lst = [[0 for a in range(0, n)] for b in range(0, n)]
	(ff, x, y, count) = (1, 0, 0, 0)
	while count < k:
		lst[x][y] = 1
		x = (x + 1) % n
		y = (y + 1) % n
		if count % n == n - 1:
			x = 0
			y = ff
			ff += 1
		count += 1
	print(res)
	for elem in lst:
		print(''.join((str(x) for x in elem)))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	di = k // n
	re = k % n
	ll = []
	if re == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		ll.append(['0'] * n)
	for i in range(k):
		ll[i % n][(i // n + i % n) % n] = '1'
	ch = ''
	for i in ll:
		ch = ''.join(i)
		print(ch)


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	m = k // n
	r = k % n
	if r:
		print(2)
		s = '1' * (m + 1) + '0' * (n - m - 1)
		for i in range(r):
			print(s)
			s = s[1:] + s[0]
		i = (m - r) % n
		s = s[:i] + '0' + s[i + 1:]
		for i in range(n - r):
			print(s)
			s = s[1:] + s[0]
	else:
		print(0)
		s = '1' * m + '0' * (n - m)
		for i in range(n):
			print(s)
			s = s[1:] + s[0]


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	table = [[0 for i in range(n)] for j in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	i = 0
	j = 0
	bias = 0
	for __ in range(k):
		table[i][j % n] = 1
		i += 1
		j += 1
		if i >= n:
			bias += 1
			i = 0
			j = bias
	for i in table:
		print(''.join(map(str, i)))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	dp = [[0] * n for i in range(n)]
	p = 0
	q = 0
	for i in range(k):
		dp[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	rmin = lmin = float('inf')
	rmax = lmax = float('-inf')
	for i in range(n):
		tmp = 0
		tmp1 = 0
		for j in range(n):
			tmp1 += dp[i][j]
			tmp += dp[j][i]
		rmin = min(rmin, tmp1)
		rmax = max(rmax, tmp1)
		lmin = min(lmin, tmp)
		lmax = max(lmax, tmp)
	print((rmax - rmin) ** 2 + (lmax - lmin) ** 2)
	for i in dp:
		print(*i, sep='')


from sys import stdout
from collections import defaultdict
import math
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	l = [[0 for x in range(n)] for y in range(n)]
	z = k // n
	re = k % n
	ans = 0
	if re > 0:
		ans = 2
	r = [z for x in range(n)]
	c = [z for x in range(n)]
	v = [z for x in range(n)]
	i = 0
	while re > 0:
		r[i] += 1
		c[i] += 1
		v[i] += 1
		re -= 1
		i += 1
	for i in range(n):
		for j in range(n):
			if r[i] > 0:
				l[i][j] = 1
				r[i] -= 1
				c[j] -= 1
	for i in range(n):
		for j in range(n):
			if l[i][j] == 1:
				if c[j] < 0:
					for k in range(v[i], n):
						if l[i][k] == 0 and c[k] > 0:
							l[i][k] = 1
							l[i][j] = 0
							c[k] -= 1
							c[j] += 1
							v[i] += 1
							break
	print(ans)
	for i in l:
		for j in i:
			stdout.write(str(j))
		stdout.write('\n')


for _ in range(int(input())):
	(N, K) = list(map(int, input().split()))
	t = K // N
	r = K % N
	if K % N == 0:
		print(0)
	else:
		print(2)
	count = r
	for i in range(N):
		for j in range(N):
			if (i + j) % N < t:
				print(1, end='')
			elif (i + j) % N == t and count > 0:
				count -= 1
				print(1, end='')
			else:
				print(0, end='')
		print()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	grid = [['0' for i in range(n)] for j in range(n)]
	co = 0
	for i in range(n):
		x = 0
		for j in range(i, i + n):
			if co == k:
				break
			grid[x][j % n] = '1'
			co += 1
			x += 1
		if co == k:
			break
	rowmax = 0
	rowmin = 999999999999
	colmax = 0
	colmin = 999999999999
	for i in range(n):
		summ = 0
		for j in range(n):
			if grid[i][j] == '1':
				summ += 1
		rowmax = max(summ, rowmax)
		rowmin = min(summ, rowmin)
	for j in range(n):
		summ = 0
		for i in range(n):
			if grid[i][j] == '1':
				summ += 1
		colmax = max(summ, colmax)
		colmin = min(summ, colmin)
	print((rowmax - rowmin) ** 2 + (colmax - colmin) ** 2)
	for i in grid:
		print(''.join(i))


from sys import stdin, stdout
import math
import heapq
t = int(stdin.readline())
for _ in range(t):
	(n, k) = map(int, stdin.readline().split())
	A = [[0] * n for _ in range(n)]
	(nn, kk, r, c) = (n, k, 0, 0)
	ans = 0
	if k % n != 0:
		ans = 2
	while nn > 0 and kk > 0:
		x = math.ceil(kk / nn)
		for _ in range(x):
			A[r][c % n] = 1
			c += 1
		nn -= 1
		kk -= x
		r += 1
	print(ans)
	for row in A:
		print(''.join(map(str, row)))


t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	matrix = [[0] * n for j in range(n)]
	a = k // n
	b = k % n
	for j in range(a):
		for l in range(n):
			matrix[(j + l) % n][l % n] = 1
	for j in range(b):
		matrix[(a + j) % n][j % n] = 1
	if b == 0:
		print(0)
		for j in range(n):
			print(''.join((str(x) for x in matrix[j])))
	else:
		print(2)
		for j in range(n):
			print(''.join((str(x) for x in matrix[j])))


def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
n = inp()

def min_index_list(l):
	min_val = l[0] + 1
	min_list = []
	for i in range(len(l)):
		if l[i] < min_val:
			print('min_val is' + str(i))
			min_val = l[i]
			min_list = [i]
		elif l[i] == min_val:
			min_list.append(i)
	return min_list
for i in range(n):
	l = inlt()
	n = l[0]
	k = l[1]
	cnt = 0
	mat = []
	for j in range(n):
		mat.append([0] * n)
	row_count = [0] * n
	col_count = [0] * n
	offset = 0
	while cnt < k:
		for j in range(n):
			mat[(j + offset) % n][j] = 1
			cnt += 1
			if cnt == k:
				break
		offset += 1
	if k == 0:
		print(0)
	elif k % n == 0:
		print(0)
	else:
		print(2)
	for r in mat:
		ans = ''
		for x in r:
			ans += str(x)
		print(ans)


import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
from collections import defaultdict
con = 10 ** 9 + 7
INF = float('inf')

def getlist():
	return list(map(int, input().split()))

def main():
	T = int(input())
	for _ in range(T):
		(N, K) = getlist()
		ans = None
		if K % N == 0:
			ans = 0
		else:
			ans = 2
		ansTable = [['0'] * N for i in range(N)]
		for k in range(K):
			i = k % N
			j = (int(k // N) + i) % N
			ansTable[i][j] = '1'
		print(ans)
		for i in range(N):
			print(''.join(ansTable[i]))
main()


import os
import sys
from io import BytesIO, IOBase

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		M = [[0] * n for i in range(n)]
		rem = k % n
		R = list()
		C = [0] * n
		for i in range(rem):
			R.append(1 + k // n)
		for i in range(n - rem):
			R.append(k // n)
		j = 0
		for i in range(len(R)):
			for _ in range(R[i]):
				M[i][j] = 1
				C[j] += 1
				j = (j + 1) % n
		print((max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2)
		for row in M:
			for val in row:
				print(val, end='')
			print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = lambda s: self.buffer.write(s.encode()) if self.writable else None

	def read(self):
		if self.buffer.tell():
			return self.buffer.read().decode('ascii')
		return os.read(self._fd, os.fstat(self._fd).st_size).decode('ascii')

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline().decode('ascii')

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

def print(*args, sep=' ', end='\n', file=sys.stdout, flush=False):
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(end)
	if flush:
		file.flush()
(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
sys.setrecursionlimit(10000)
main()


import sys
import math
import heapq
from collections import defaultdict, deque
input = sys.stdin.readline

def r():
	return int(input())

def rm():
	return map(int, input().split())

def rl():
	return list(map(int, input().split()))
for _ in range(r()):
	(n, k) = rm()
	arr = [[0] * n for i in range(n)]
	brr = [0] * n
	mini = k // n
	maxi = mini + (1 if k % n != 0 else 0)
	brr[0] = maxi
	if k % n != 0:
		brr[k % n] = -1
	rec = 0
	for i in range(n):
		rec = rec + brr[i]
		for j in range(i, i + rec):
			arr[i][j % n] = 1
	print(2 * (maxi - mini) ** 2)
	for i in range(n):
		for j in range(n):
			print(arr[i][j], end='')
		print()


t = int(input())

def ar(n, l, i):
	a = '1' * l + '0' * (n - l)
	b = a[0:n - i]
	c = a[n - i:n]
	return c + b
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	for j in range(k % n):
		a = ar(n, k // n + 1, j)
		print(a)
	for j in range(k % n, n):
		a = ar(n, k // n, j)
		print(a)


t = int(input())
while t:
	q = list(map(int, input().split()))
	(n, k) = (q[0], q[1])
	s = [[0] * n for x in range(n)]
	(h, r) = (k // n, k % n)
	if h >= 1:
		for x in range(0, n):
			for y in range(0, h):
				if x + y < n:
					s[x][x + y] = 1
				else:
					s[x][x + y - n] = 1
		for x in range(1, r + 1):
			if h + x - 1 < n:
				s[x - 1][h + x - 1] = 1
			else:
				s[x - 1][h + x - 1 - n] = 1
	else:
		for x in range(0, r):
			s[x][x] = 1
	if r == 0:
		print('0')
	else:
		print('2')
	for x in range(0, n):
		for y in range(0, n):
			print(s[x][y], end='')
		print()
	t -= 1


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	grid = [[0 for _ in range(n)] for _ in range(n)]
	q = k // n
	r = k % n
	c = 0
	for ro in range(q):
		for i in range(n):
			temp = (c + i) % n
			grid[i][temp] = 1
		c += 1
	for ro in range(r):
		temp = (c + ro) % n
		grid[ro][temp] = 1
	if r == 0:
		print(0)
	else:
		print(2)
	for ro in grid:
		print(*ro, sep='')


from sys import stdin, setrecursionlimit, stdout
setrecursionlimit(1000000)
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin
from heapq import heapify, heappop, heappush, heappushpop, heapreplace

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
res = ['YES', 'NO']
test_case = ii()
while test_case:
	test_case -= 1
	(n, k) = mi()
	a = [0] * (n * n)
	i = 0
	while k:
		a[i] = 1
		i += n + 1
		k -= 1
		if i >= n * n:
			i -= n * n
	ans = []
	for j in range(n):
		ans.append([i for i in a[j * n:j * n + n]])
	r = []
	c = []
	for i in ans:
		r.append(sum(i))
	for i in range(n):
		s = 0
		for j in range(n):
			s += ans[j][i]
		c.append(s)
	print((max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2)
	for i in ans:
		print(*i, sep='')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	grid = [[0] * n for _ in range(n)]
	x = y = 0
	for _ in range(k):
		grid[x][y] = 1
		y += 1
		x += 1
		if y >= n:
			y = 0
			x += 1
		(x, y) = (x % n, y % n)
	print(2 if k % n else 0)
	print('\n'.join((''.join(map(str, e)) for e in grid)))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = [[1] * n for i in range(n)]
	if n ** 2 > k:
		k = n ** 2 - k
		i = j = 0
		c = 1
		m = 0
		while k != 0:
			if m == n:
				i = (i + c) % n
				m = 0
			if i == n:
				i = i % n
			if j == n:
				j = 0
			l[j][i] = 0
			k -= 1
			i += 1
			m += 1
			j += 1
	mxr = mnr = sum(l[0])
	mxc = mnc = sum([l[i][0] for i in range(n)])
	for i in range(n):
		s = sum(l[i])
		mxr = max(s, mxr)
		mnr = min(s, mnr)
		s = sum([l[j][i] for j in range(n)])
		mnc = min(s, mnc)
		mxc = max(s, mxc)
	print((mxr - mnr) ** 2 + (mxc - mnc) ** 2)
	for i in range(n):
		print(*l[i], sep='')


import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	d = k // n
	if k % n == 0:
		print(0)
	else:
		print(2)
	rem = k % n
	for j in range(n):
		k1 = d
		if rem:
			rem -= 1
			k1 += 1
		s1 = '1' * min(k1, n - j)
		s2 = ''
		if n - j > k1:
			s1 += '0' * (n - j - k1)
			s2 += '0' * j
		else:
			s2 += '1' * (k1 - n + j)
			s2 += '0' * (n - k1)
		print(s2 + s1)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	res = [['0'] * n for _ in range(n)]
	if k % n:
		print(2)
	else:
		print(0)
	for d in range(n):
		for i in range(n):
			if k == 0:
				break
			res[i][(i + d) % n] = '1'
			k -= 1
	for r in res:
		print(''.join(r))


import pprint

def func(n, k):
	mod = k % n
	t = k // n
	b = mod
	s = n - mod
	if k % n == 0:
		print(0)
	else:
		print(2)
	A = [[0 for i in range(n)] for j in range(n)]
	for i in range(b):
		for j in range(i, i + t + 1):
			A[i][j % n] = 1
	for i in range(b, n):
		for j in range(i, i + t):
			A[i][j % n] = 1
	for i in range(len(A)):
		for j in range(len(A)):
			print(A[i][j], end='')
		print()
t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	func(n, k)


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	ans = []
	for i in range(n):
		ans.append([0] * n)
	for i in range(k):
		ans[(i + i // n) % n][i % n] += 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join([str(x) for x in ans[i]]))


input = __import__('sys').stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	print(2 if k % n else 0)
	ans = [['0'] * n for i in range(n)]
	x = y = 0
	while k:
		k -= 1
		ans[x][y] = '1'
		y = (y + 1 + int(x == n - 1)) % n
		x = (x + 1) % n
	for i in ans:
		print(''.join(i))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	ANS = [[0] * n for i in range(n)]
	o = k // n
	m = k - o * n
	now = 0
	for i in range(n):
		if i < m:
			for j in range(o + 1):
				ANS[i][now] = 1
				now = (now + 1) % n
		else:
			for j in range(o):
				ANS[i][now] = 1
				now = (now + 1) % n
	if m == 0:
		print(0)
	else:
		print(2)
	for ans in ANS:
		print(''.join(map(str, ans)))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if not k % n:
		print(0)
	else:
		print(2)
	l = [[0] * n for i in range(n)]
	c = 0
	while k:
		for i in range(n):
			l[(i + c) % n][i] = 1
			k -= 1
			if not k:
				break
		c += 1
	for i in l:
		for j in i:
			print(j, end='')
		print()


from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def I():
	return int(sys.stdin.readline())

def LS():
	return [list(x) for x in sys.stdin.readline().split()]

def S():
	res = list(sys.stdin.readline())
	if res[-1] == '\n':
		return res[:-1]
	return res

def IR(n):
	return [I() for i in range(n)]

def LIR(n):
	return [LI() for i in range(n)]

def SR(n):
	return [S() for i in range(n)]

def LSR(n):
	return [LS() for i in range(n)]
sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():

	def mat(n, r):
		a = []
		k = [0] * (n - r) + [1] * r
		k *= 2
		for i in range(1, n + 1)[::-1]:
			a.append(k[i:i + n])
		return a
	t = I()
	for _ in range(t):
		(n, k) = LI()
		m = k // n
		r = k % n
		a = [m + 1 if i < r else m for i in range(n)]
		p = -r % n
		ans = mat(n, m)
		for i in range(r):
			ans[i][i] = 1
		print(2 * (a[0] - a[-1]))
		for i in ans:
			print(*i, sep='')
	return
solve()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0] * n for i in range(n)]
	i = 0
	j = 0
	if k % n == 0:
		print(0)
	else:
		print(2)
	while k > 0:
		k -= 1
		a[i][j] = 1
		i += 1
		j = (j + 1) % n
		if i == n:
			i = 0
			j = (j + 1) % n
	for row in a:
		print(*row, sep='')


for i in [*open(0)][1:]:
	(n, k) = map(int, i.split())
	m = [[0 for i in range(n)] for i in range(n)]
	i = 0
	j = 0
	minnr = n
	maxxr = 0
	minnc = n
	maxxc = 0
	n -= 1
	while k:
		m[i][j] = 1
		if i == n:
			i = 0
		elif j == n:
			j = 0
			i += 1
		else:
			i += 1
			j += 1
		k -= 1
	for i in range(n + 1):
		sum1 = 0
		sum2 = 0
		for j in range(n + 1):
			sum1 += m[i][j]
			sum2 += m[j][i]
		minnr = min(sum1, minnr)
		maxxr = max(sum1, maxxr)
		minnc = min(sum2, minnc)
		maxxc = max(sum2, maxxc)
	print((maxxc - minnc) ** 2 + (maxxr - minnr) ** 2)
	for i in m:
		for j in i:
			print(j, end='')
		print()


debug = False
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0] * (n + 1) for i in range(n + 1)]
	(p, q) = (0, 0)
	while k > 0:
		mat[p + 1][q + 1] = 1
		p += 1
		q += 1
		q %= n
		if p == n:
			p = 0
			q += 1
			q %= n
		k -= 1
	if debug:
		print('After i j k', i, j, k)
	(MaxR, MinR, MaxC, MinC) = (0, float('inf'), 0, float('inf'))
	for i in range(1, n + 1):
		(SumR, SumC) = (0, 0)
		for j in range(1, n + 1):
			SumR += mat[i][j]
			SumC += mat[j][i]
		MinR = min(MinR, SumR)
		MinC = min(MinC, SumC)
		MaxR = max(MaxR, SumR)
		MaxC = max(MaxC, SumC)
	if debug:
		print(MaxC, MinC, MaxR, MinR)
	print((MaxC - MinC) ** 2 + (MaxR - MinR) ** 2)
	for l in range(1, n + 1):
		print(*mat[l][1:], sep='')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	t = [[0 for i in range(n)] for j in range(n)]
	xx = k // n
	r = k % n
	m = 0
	for i in range(n):
		for j in range(xx):
			t[i][m % n] = 1
			m += 1
		if r > 0:
			t[i][m % n] = 1
			m += 1
			r -= 1
	rr = 301
	ll = -1
	for i in t:
		xxx = sum(i)
		if xxx > ll:
			ll = xxx
		if xxx < rr:
			rr = xxx
	rr = 301
	ll = -1
	for i in range(n):
		xxx = sum((t[j][i] for j in range(n)))
		if xxx < rr:
			rr = xxx
		if xxx > ll:
			ll = xxx
	print(2 * (ll - rr) ** 2)
	for i in t:
		print(''.join((str(j) for j in i)))


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	(p, q) = (0, 0)
	A = [[0] * n for i in range(n)]
	for i in range(1, k + 1):
		A[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	maxC = -1
	minC = float('inf')
	for i in range(n):
		c = 0
		for j in range(n):
			c += A[j][i]
		maxC = max(maxC, c)
		minC = min(minC, c)
	maxR = -1
	minR = float('inf')
	for i in range(n):
		r = sum(A[i])
		maxR = max(maxR, r)
		minR = min(minR, r)
	print((maxR - minR) ** 2 + (maxC - minC) ** 2)
	for row in A:
		print(''.join([str(i) for i in row]))


import io, os
from collections import deque
RL = lambda : list(map(int, input().split(' ')))
T = int(input())
for _ in range(T):
	(n, k) = RL()
	a = [['0' for i in range(n)] for j in range(n)]
	inix = n
	iniy = 0
	i = 0
	j = 0
	flag = 0
	while k:
		a[i][j] = '1'
		k -= 1
		i += 1
		j += 1
		if i == n or j == n:
			if flag == 0:
				inix -= 1
				i = inix
				j = 0
				flag = 1
			else:
				iniy += 1
				i = 0
				j = iniy
				flag = 0
	sur = []
	suc = []
	for i in range(n):
		su = 0
		for j in range(n):
			su += int(a[i][j])
		sur.append(su)
	for i in range(n):
		su = 0
		for j in range(n):
			su += int(a[j][i])
		suc.append(su)
	print((max(sur) - min(sur)) ** 2 + (max(suc) - min(suc)) ** 2)
	for i in range(n):
		print(''.join(a[i]))


t = int(input())

def print_row(n, index, unos):
	row = ['0'] * index
	row += ['1'] * unos
	row += ['0'] * (n - (index + unos))
	if len(row) >= n:
		for (i, v) in enumerate(row[n:]):
			row[i] = v
	print(''.join(row[:n]))

def print_matrix(n, k):
	div = k // n
	mod = k % n
	for i in range(n):
		if i < mod:
			print_row(n, i, div + 1)
		else:
			print_row(n, i, div)
for _ in range(t):
	(n, k) = tuple(map(int, input().split()))
	if k == 0:
		print(0)
		for _ in range(n):
			print(''.join(['0'] * n))
	elif k == 1:
		if n == 1:
			print(0)
			print(1)
		else:
			print(2)
			print_matrix(n, 1)
	elif k % n == 0:
		print(0)
		print_matrix(n, k)
	else:
		print(2)
		print_matrix(n, k)


def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		a = [[0] * n for i in range(n)]
		kk = k
		for i in range(n):
			l = i
			for j in range(n):
				if k > 0:
					k -= 1
					a[l % n][j % n] = 1
					l += 1
				else:
					break
		print(2 if kk % n else 0)
		for i in a:
			print(''.join(map(str, i)))
	return
main()


t = int(input())
for _ in range(t):
	(n, k) = tuple(map(int, input().rstrip().split()))
	grid = [[0] * n for _ in range(n)]
	a = 0
	for d in range(n):
		if k == 0:
			break
		for r in range(n):
			c = (r + d) % n
			if k == 0:
				a = 2
				break
			grid[r][c] = 1
			k -= 1
	print(a)
	for row in grid:
		for val in row:
			print(val, end='')
		print()


from sys import stdin
from bisect import bisect_left as bl
from bisect import bisect_right as br

def input():
	return stdin.readline()[:-1]

def intput():
	return int(input())

def sinput():
	return input().split()

def intsput():
	return map(int, sinput())

class RangedList:

	def __init__(self, start, stop, val=0):
		self.shift = 0 - start
		self.start = start
		self.stop = stop
		self.list = [val] * (stop - start)

	def __setitem__(self, key, value):
		self.list[key + self.shift] = value

	def __getitem__(self, key):
		return self.list[key + self.shift]

	def __repr__(self):
		return str(self.list)

	def __iter__(self):
		return iter(self.list)

def dprint(*args, **kwargs):
	if debugging:
		print(*args, **kwargs)

def fill(g, c):
	g[c[0]][c[1]] = 1

def gprint(g):
	for l in g:
		print(''.join(map(str, l)))

def calc(g):
	minr = sum(g[0])
	maxr = sum(g[0])
	for l in g:
		minr = min(minr, sum(l))
		maxr = max(maxr, sum(l))
	minc = sum([g[x][0] for x in range(len(g))])
	maxc = sum([g[x][0] for x in range(len(g))])
	for k in range(len(g)):
		minc = min(minc, sum([g[x][k] for x in range(len(g))]))
		maxc = max(maxc, sum([g[x][k] for x in range(len(g))]))
	return (minr - maxr) ** 2 + (minc - maxc) ** 2

def increment(p, n):
	p[0] = (p[0] + 1) % n
	p[1] = (p[1] + 1) % n
debugging = 1
t = intput()
for _ in range(t):
	(n, k) = intsput()
	grid = [[0] * n for _ in range(n)]
	pos = [0, 0]
	while True:
		while grid[pos[0]][pos[1]] == 0 and k:
			fill(grid, pos)
			k -= 1
			increment(pos, n)
		if k == 0:
			break
		pos[1] = (pos[1] + 1) % n
	print(calc(grid))
	gprint(grid)


def solve(n, k):
	grid = [[0] * n for _ in range(n)]
	i = 0
	j = 0
	while k > 0:
		grid[i % n][(i + j) % n] += 1
		k -= 1
		i += 1
		if i % n == 0:
			j += 1
	r_min = n
	r_max = 0
	c_min = n
	c_max = 0
	for r in range(n):
		r_max = max(r_max, sum(grid[r]))
		r_min = min(r_min, sum(grid[r]))
	for c in range(n):
		c_sum = sum((grid[i][c] for i in range(n)))
		c_max = max(c_max, c_sum)
		c_min = min(c_min, c_sum)
	ans = (r_max - r_min) ** 2 + (c_max - c_min) ** 2
	print(ans)
	for i in range(n):
		temp = ''
		for j in range(n):
			temp += str(grid[i][j])
		print(temp)
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	solve(n, k)


def f(m, n):
	R = [0] * n
	C = [0] * n
	for i in range(n):
		for j in range(n):
			R[i] += m[i][j]
			C[i] += m[j][i]
	return (max(R) - min(R)) ** 2 + (max(C) - min(C)) ** 2
for _ in range(int(input())):
	(n, k) = (int(i) for i in input().split())
	matrix = [[0] * n for _ in range(n)]
	i = j = 0
	while k:
		for __ in range(n):
			matrix[i % n][j % n] = 1
			i += 1
			j += 1
			k -= 1
			if k == 0:
				break
		j += 1
	print(f(matrix, n))
	for i in range(n):
		for j in range(n):
			print(matrix[i][j], end='')
		print()


t = int(input())

def fill_right(mat, i, j, k):
	r = len(mat)
	c = len(mat[0])
	while i < r and j < c and (k > 0):
		mat[i][j] = 1
		i += 1
		j += 1
		k -= 1
	if i < r and j < c:
		return (mat, k, False)
	return (mat, k, True)
for i in range(t):
	(n, k) = [int(x) for x in input().split(' ')]
	mat = [[0 for j in range(n)] for p in range(n)]
	min_val = 0
	for j in range(n):
		if k == 0:
			break
		min_val = 2
		(mat, k, comp) = fill_right(mat, j, 0, k)
		if j == 0 and comp == True:
			min_val = 0
		if j == 0:
			continue
		if k == 0:
			break
		(mat, k, comp) = fill_right(mat, 0, n - j, k)
		if comp:
			min_val = 0
		else:
			min_val = 2
	print(min_val)
	for m in mat:
		print(''.join([str(x) for x in m]))


from math import *
from collections import *
from bisect import *
import sys
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	(n, k) = map(int, input().split())
	r = [[0 for i in range(n)] for j in range(n)]
	(row, coli) = (0, 0)
	for i in range(k):
		r[row][coli] = 1
		row += 1
		coli = (coli + 1) % n
		if row == n:
			row = 0
			coli = (coli + 1) % n
	ro = []
	col = []
	for i in r:
		ro.append(sum(i))
	for i in range(n):
		cc = 0
		for j in range(n):
			cc += r[j][i]
		col.append(cc)
	ro.sort()
	col.sort()
	ff = ro[-1] - ro[0]
	ss = col[-1] - col[0]
	ff = ff * ff
	ss = ss * ss
	print(ff + ss)
	for i in r:
		print(*i, sep='')


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def val(a):
	(mrow1, mrow2) = (69696969, 0)
	for i in range(n):
		s = 0
		for j in range(n):
			s += a[i][j]
		mrow1 = min(mrow1, s)
		mrow2 = max(mrow2, s)
	(mrow3, mrow4) = (69696969, 0)
	for i in range(n):
		s = 0
		for j in range(n):
			s += a[j][i]
		mrow3 = min(mrow3, s)
		mrow4 = max(mrow4, s)
	return (mrow2 - mrow1) ** 2 + (mrow4 - mrow3) ** 2

def printgrid(a):
	print(val(a))
	for i in a:
		print(''.join((str(k) for k in i)))
for _ in range(int(input()) if True else 1):
	(n, k) = map(int, input().split())
	a = [[0 for __ in range(n)] for ___ in range(n)]
	for i in range(n):
		if not k:
			break
		a[i][i] = 1
		k -= 1
	if not k:
		printgrid(a)
		continue
	b = [i for i in range(n)]
	b += b
	for i in range(1, n):
		if not k:
			break
		for j in range(n):
			if not k:
				break
			a[j][b[i + j]] = 1
			k -= 1
	printgrid(a)


import sys
input = sys.stdin.readline
import heapq
import copy
import math

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 1000000007
	limit = 10 ** 18
	for test in range(tests):
		[n, k] = inlt()
		if k != 0:
			no = k // n
			if k % n == 0:
				ans = 0
				left = 0
			else:
				ans = 2
				left = k % n
		else:
			no = 0
			ans = 0
			left = 0
		grid = [['0' for i in range(n)] for j in range(n)]
		for i in range(n):
			for j in range(no):
				grid[i][(i + j) % n] = '1'
		for i in range(left):
			grid[i][(i + no) % n] = '1'
		print(ans)
		for i in range(n):
			print(''.join(grid[i]))
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0] * n for _ in range(n)]
	for i in range(n):
		b = False
		for j in range(n):
			if i * n + j == k:
				b = True
				break
			mat[(i + j) % n][j] = 1
		if b:
			break
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print()


t = int(input())
for _ in range(t):
	(n, k) = [int(x) for x in input().split()]
	if k % n == 0:
		print('0')
	else:
		print('2')
	grid = [['0'] * n for _ in range(n)]
	for i in range(k // n):
		for r in range(n):
			grid[r][(r + i) % n] = '1'
	for r in range(k % n):
		grid[r][(r + i + 1) % n] = '1'
	for row in grid:
		print(''.join(row))


import os
import sys, math
from io import BytesIO, IOBase

def main():
	t = int(input())
	for case in range(t):
		(n, k) = list(map(int, input().split()))
		ctr = [0 for i in range(n)]
		ctc = [0 for i in range(n)]
		r = 0
		c = 0
		ans = []
		for i in range(n):
			l = [0 for j in range(n)]
			ans.append(l)
		for i in range(k):
			if i != 0 and i % n == 0:
				c = (c + 1) % n
			ans[r][c] = 1
			ctr[r] += 1
			ctc[c] += 1
			r = (r + 1) % n
			c = (c + 1) % n
		print((max(ctr) - min(ctr)) ** 2 + (max(ctc) - min(ctc)) ** 2)
		for i in range(n):
			for j in range(n):
				print(ans[i][j], end='')
			print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
(inp, ip) = (lambda : int(input()), lambda : [int(w) for w in input().split()])
for _ in range(inp()):
	(n, k) = ip()
	f = 2 if k % n else 0
	x = [[0] * n for i in range(n)]
	for j in range(n):
		for i in range(n):
			if k == 0:
				break
			x[i][(i + j) % n] = 1
			k -= 1
		if k == 0:
			break
	print(f)
	for i in range(n):
		x[i] = [str(j) for j in x[i]]
		print(''.join(x[i]))


t = int(input())
for case in range(t):
	(n, k) = list(map(int, input().split(' ')))
	if k % n == 0:
		print(0)
		num = k // n
		for i in range(n):
			for j in range(n):
				if (i + j) % n < num:
					print(1, end='')
				else:
					print(0, end='')
			print('')
	else:
		print(2)
		num = k // n
		longer = k % n
		for i in range(n):
			for j in range(n):
				if j >= longer:
					if (i + j) % n < num:
						print(1, end='')
					else:
						print(0, end='')
				elif (i + j) % n < num + 1:
					print(1, end='')
				else:
					print(0, end='')
			print('')


t = int(input())
while t > 0:
	(n, k) = map(int, input().split())
	matrix = []
	for i in range(n):
		temp = []
		for j in range(n):
			temp.append(0)
		matrix.append(temp)
	if k > 0:
		temp = k // n
		rem = k % n
		for i in range(temp):
			for j in range(n):
				matrix[j][(j + i) % n] = 1
		for i in range(rem):
			matrix[i][(i + temp) % n] = 1
		min_row = n
		max_row = 0
		for i in range(n):
			temp = sum(matrix[i])
			if temp > max_row:
				max_row = temp
			if temp < min_row:
				min_row = temp
		max_col = 0
		min_col = n
		for i in range(n):
			su = 0
			for j in range(n):
				su += matrix[j][i]
			if su > max_col:
				max_col = su
			if su < min_col:
				min_col = su
		print((max_row - min_row) ** 2 + (max_col - min_col) ** 2)
		for i in range(n):
			for j in range(n):
				print(matrix[i][j], end='')
			print()
	else:
		print(0)
		for i in range(n):
			for j in range(n):
				print(0, end='')
			print()
	t -= 1


import sys
from fractions import gcd
from math import ceil, sqrt, sin, pi, tan
from collections import defaultdict
read = sys.stdin.buffer.readline
import heapq
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())
as0 = ord('0')
as1 = ord('1')
for _ in range(cin()):
	(n, k) = mi()
	mat = [[0 for i in range(n)] for j in range(n)]
	dis = 0
	while k:
		if dis == n:
			break
		for i in range(n):
			k -= 1
			mat[i][(i + dis) % n] = 1
			if k == 0:
				break
		dis += 1
	(mxr, mnr) = (0, 1000000)
	(mxc, mnc) = (0, 1000000)
	for i in range(n):
		smr = sum(mat[i])
		smc = 0
		for j in range(n):
			smc += mat[j][i]
		mxc = max(mxc, smc)
		mnc = min(mnc, smc)
		mxr = max(mxr, smr)
		mnr = min(mnr, smr)
	print(pow(mxr - mnr, 2) + pow(mxc - mnc, 2))
	for el in mat:
		for ell in el:
			print(ell, end='')
		print()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	mod = k // n
	rem = k % n
	l = [[0 for j in range(n)] for k in range(n)]
	for j in range(n):
		for k in range(mod):
			if j + k + 1 >= n:
				l[j][j + 1 + k - n] = 1
			else:
				l[j][j + 1 + k] = 1
	j = 0
	for k in range(rem):
		l[j][j] = 1
		j += 1
	if rem == 0:
		print(0)
	else:
		print(2)
	for j in range(n):
		print(*l[j], sep='')


for i in range(int(input())):
	a = []
	(n, k) = map(int, input().split())
	if k >= n ** 2 // 2:
		k = n ** 2 - k
		flag = 0
	else:
		flag = 1
	initk = k
	abc = k // n
	cde = k % n
	for p in range(n):
		b = n * [(flag + 1) % 2]
		cnt = 0
		cde1 = cde
		for v in range(n):
			if initk >= 2 * n and p >= n - abc and (k > 0):
				b[(v + p) % n] = flag
				cnt += 1
				k -= 1
				if cde1 > p and cnt == abc + 1:
					break
				if cde1 <= p and cnt == abc:
					break
			elif v >= p and k > 0:
				if p < cde:
					b[v] = flag
					k -= 1
					cnt += 1
					if cnt == abc + 1:
						break
				else:
					b[v] = flag
					k -= 1
					cnt += 1
					if cnt == abc:
						break
		a.append(b)
	max_string = 0
	min_string = n + 1
	sum_array = n * [0]
	for z in range(n):
		if sum(a[z]) > max_string:
			max_string = sum(a[z])
		if sum(a[z]) < min_string:
			min_string = sum(a[z])
		for f in range(n):
			sum_array[f] += a[z][f]
	max_column = max(sum_array)
	min_column = min(sum_array)
	print((max_string - min_string) ** 2 + (max_column - min_column) ** 2)
	for k in range(n):
		print(*a[k], sep='')


def f(mat, n):
	maxRow = -1
	maxCol = -1
	minRow = pow(10, 10)
	minCol = pow(10, 10)
	for i in range(0, n):
		sr = 0
		for j in range(0, n):
			sr += mat[i][j]
		if sr > maxRow:
			maxRow = sr
		if sr < minRow:
			minRow = sr
	for i in range(0, n):
		sc = 0
		for j in range(0, n):
			sc += mat[j][i]
		if sc > maxCol:
			maxCol = sc
		if sc < minCol:
			minCol = sc
	return pow(maxRow - minRow, 2) + pow(maxCol - minCol, 2)

def findPlace(mat, n, rSet, cSet):
	for i in range(0, n):
		for j in range(0, n):
			if i not in rSet and j not in cSet and (mat[i][j] == 0):
				return (i, j)
	return (-1, -1)

def solve(n, k, mat):
	rSet = set()
	cSet = set()
	for i in range(0, k):
		place = findPlace(mat, n, rSet, cSet)
		if place == (-1, -1):
			rSet = set()
			cSet = set()
			place = findPlace(mat, n, rSet, cSet)
		rSet.add(place[0])
		cSet.add(place[1])
		mat[place[0]][place[1]] = 1

def solve2(n, k, mat):
	ctr = 0
	add = 0
	while ctr < k:
		for i in range(0, n):
			mat[i][(i + add) % n] = 1
			ctr += 1
			if ctr >= k:
				break
		add += 1
	print(f(mat, n))
	for i in range(0, n):
		for j in range(0, n):
			print(mat[i][j], end='')
		print()
for _ in range(int(input())):
	liStr = input().split()
	n = int(liStr[0])
	k = int(liStr[1])
	mat = []
	for i in range(0, n):
		li = []
		for j in range(0, n):
			li.append(0)
		mat.append(li)
	solve2(n, k, mat)


def main():
	n = int(input())
	for i in range(n):
		solve()

def solve():
	(n, k) = list(map(int, input().split(' ')))
	arr = [[0 for i in range(n)] for i in range(n)]
	flag = False
	max_row = 0
	offset = 0
	while k >= n:
		for i in range(n):
			arr[(i + offset) % n][i] = 1
			max_row += 1
		k -= n
		offset += 1
	for i in range(k):
		arr[(i + offset) % n][i] = 1
		flag = True
	if flag == False:
		print(0)
	else:
		print(2 * (max_row - (max_row - 1)) ** 2)
	for i in arr:
		print(''.join([str(x) for x in i]))
main()


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def MI():
	return map(int, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RA():
	return map(int, open(0).read().split())

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in range(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in range(base ** n):
		s = [tb // base ** bt % base for bt in range(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print(['No', 'Yes'][x])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()

class Tree:

	def __init__(self, inp_size=None, ls=None, init=True, index=1):
		self.LCA_init_stat = False
		self.ETtable = []
		if init:
			if ls == None:
				self.stdin(inp_size, index=index)
			else:
				self.node_size = len(ls) + 1
				(self.edges, _) = GI(self.node_size, self.node_size - 1, ls, index=index)
		return

	def stdin(self, inp_size=None, index=1):
		if inp_size == None:
			self.node_size = int(input())
		else:
			self.node_size = inp_size
		(self.edges, _) = GI(self.node_size, self.node_size - 1, index=index)
		return

	def listin(self, ls, index=0):
		self.node_size = len(ls) + 1
		(self.edges, _) = GI(self.node_size, self.node_size - 1, ls, index=index)
		return

	def dfs(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.node_size
		v[x] = root_v
		while q:
			c = q.pop()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
		return v

	def bfs(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.node_size
		v[x] = root_v
		while q:
			c = q.popleft()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
		return v

	def parent(self, x):
		return self.dfs(0, func=lambda pr, prv, nx, dist: pr, root_v=-1)

	def topological_sort(self, x):
		tps = []
		q = deque([x])
		v = [None] * self.node_size
		v[x] = 0
		while q:
			c = q.popleft()
			tps.append(c)
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = 0
		return tps

	def EulerTour(self, x):
		q = deque()
		q.append(x)
		self.depth = [None] * self.node_size
		self.depth[x] = 0
		self.ETtable = []
		self.ETdepth = []
		self.ETin = [-1] * self.node_size
		self.ETout = [-1] * self.node_size
		cnt = 0
		while q:
			c = q.pop()
			if c < 0:
				ce = ~c
			else:
				ce = c
				for (nb, d) in self.edges[ce]:
					if self.depth[nb] == None:
						q.append(~ce)
						q.append(nb)
						self.depth[nb] = self.depth[ce] + 1
			self.ETtable.append(ce)
			self.ETdepth.append(self.depth[ce])
			if self.ETin[ce] == -1:
				self.ETin[ce] = cnt
			else:
				self.ETout[ce] = cnt
			cnt += 1
		return

	def doubling_LCA(self, root, x, y):
		if self.LCA_init_stat == False:
			self.depth = [None] * self.node_size
			self.depth = self.bfs(0, func=lambda pr, prv, nxt, dist: prv + 1)
			self.par = self.bfs(0, func=lambda pr, prv, nxt, dist: pr)
			self.db = [self.par]
			for i in range(self.node_size.bit_length()):
				self.db += [[self.db[-1][self.db[-1][i]] for i in range(self.node_size)]]
			self.LCA_init_stat = True
		dx = self.depth[x]
		dy = self.depth[y]
		if dx > dy:
			(dx, dy) = (dy, dx)
		c = self.node_size.bit_length()
		while c > 0:
			if dx + c <= dy:
				x = self.db[c][x]
				dx += 1 << c
			c >>= 1
		if x == y:
			return x
		c = self.node_size.bit_length()
		while c > 0:
			if self.db[c][x] != self.db[c][y]:
				x = self.db[c][x]
				y = self.db[c][y]
			c >>= 1
		return self.par[x]

	def LCA_init(self, root):
		self.EulerTour(root)
		self.st = SparseTable(self.ETdepth, init_func=min, init_idl=inf)
		self.LCA_init_stat = True
		return

	def LCA(self, root, x, y):
		if self.LCA_init_stat == False:
			self.LCA_init(root)
		(xin, xout) = (self.ETin[x], self.ETout[x])
		(yin, yout) = (self.ETin[y], self.ETout[y])
		a = min(xin, yin)
		b = max(xout, yout, xin, yin)
		id_of_min_dep_in_et = self.st.query_id(a, b + 1)
		return self.ETtable[id_of_min_dep_in_et]

	def __str__(self):
		return str(self.edges)

	def show(self):
		if all([all([d == 1 for (nd, d) in e]) for e in self.edges]):
			print([[nd for (nd, d) in e] for e in self.edges])
		else:
			print(self)

	def dfs2(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.node_size
		v[x] = root_v
		dfs_tr = [x]
		while q:
			c = q.pop()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
					dfs_tr += (nb,)
		return (v, dfs_tr)

class SparseTable:

	def __init__(self, ls, init_func=min, init_idl=float('inf')):
		self.func = init_func
		self.idl = init_idl
		self.size = len(ls)
		self.N0 = self.size.bit_length()
		self.table = [ls[:]]
		self.index = [list(range(self.size))]
		self.lg = [0] * (self.size + 1)
		for i in range(2, self.size + 1):
			self.lg[i] = self.lg[i >> 1] + 1
		for i in range(self.N0):
			tmp = [self.func(self.table[i][j], self.table[i][min(j + (1 << i), self.size - 1)]) for j in range(self.size)]
			tmp_id = [self.index[i][j] if self.table[i][j] == self.func(self.table[i][j], self.table[i][min(j + (1 << i), self.size - 1)]) else self.index[i][min(j + (1 << i), self.size - 1)] for j in range(self.size)]
			self.table += [tmp]
			self.index += [tmp_id]

	def query(self, l, r):
		if r > self.size:
			r = self.size
		N = self.lg[r - l]
		return self.func(self.table[N][l], self.table[N][max(0, r - (1 << N))])

	def query_id(self, l, r):
		if r > self.size:
			r = self.size
		N = self.lg[r - l]
		(a, b) = (self.index[N][l], self.index[N][max(0, r - (1 << N))])
		if self.table[0][a] == self.func(self.table[N][l], self.table[N][max(0, r - (1 << N))]):
			b = a
		return b

	def right_bound(self, pos, x):
		k = (self.size - pos).bit_length()
		for j in range(k)[::-1]:
			nx = pos + (1 << j)
			if nx < n and self.query(pos, nx + 1) <= x:
				pos += 1 << j
		return pos

	def left_bound(self, pos, x):
		k = pos.bit_length()
		for j in range(k)[::-1]:
			nx = pos - (1 << j)
			if 0 <= nx and self.query(nx, pos + 1) <= x:
				pos -= 1 << j
		return pos

	def __str__(self):
		return str(self.table[0])

	def print(self):
		for i in self.table:
			print(*i)
show_flg = False
show_flg = True
ans = 0
for _ in range(I()):
	ans = 0
	(n, k) = LI()
	a = [['0'] * n for i in range(n)]
	(x, y) = (0, 0)
	for i in range(k):
		a[y][x] = '1'
		x += 1
		y += 1
		if y == n:
			x += 1
		x %= n
		y %= n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in a:
		print(''.join(i))


T = int(input())
for _ in range(T):
	(n, k) = list(map(int, input().split()))
	a = [['0' for _ in range(n)] for _ in range(n)]
	r = [0 for _ in range(n)]
	c = [0 for _ in range(n)]
	cnt = 0
	finished = False
	for j in range(n):
		for i in range(n):
			if cnt >= k:
				finished = True
				break
			x = i
			y = (j + i) % n
			a[x][y] = '1'
			r[x] += 1
			c[y] += 1
			cnt += 1
		if finished:
			break
	ans = (max(r) - min(r)) ** 2 + (max(c) - min(c)) ** 2
	mat = '\n'.join([''.join(row) for row in a])
	print(ans)
	print(mat)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	print(2 if k % n else 0)
	grid = [[0] * n for _ in range(n)]
	for i in range(n):
		if k == 0:
			break
		grid[i][i] = 1
		k -= 1
	else:
		for i in range(n - 1):
			(x, y) = (n - 1 - i, 0)
			for j in range(x, n):
				if k:
					grid[x][y] = 1
					x += 1
					y += 1
					k -= 1
				else:
					break
			(x, y) = (0, i + 1)
			for j in range(i + 1, n):
				if k:
					grid[x][y] = 1
					x += 1
					y += 1
					k -= 1
				else:
					break
			if not k:
				break
	for i in range(n):
		for j in range(n):
			print(grid[i][j], end='')
		print()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = [[0 for i in range(n)] for j in range(n)]
	p = q = 0
	l = 1
	for i in range(n):
		for j in range(k // n):
			a[i][(i + j) % n] = 1
	for i in range(k % n):
		a[i][(i + k // n) % n] = 1
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(map(str, a[i])))


for i in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	ones = k // n
	mat = [[0 for i in range(n)] for j in range(n)]
	extra = k - ones * n
	if extra == 0:
		ans = 0
	else:
		ans = 2
	for it in range(ones):
		for i in range(n):
			mat[(i + it) % n][i] = 1
	if extra > 0:
		for i in range(extra):
			mat[(i + ones) % n][i] = 1
	print(ans)
	for x in mat:
		for y in x:
			print(y, end='')
		print()


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = [[0 for i in range(n)] for i in range(n)]
	t = k // n
	z = [t for i in range(n)]
	t = k % n
	for i in range(n):
		if t == 0:
			break
		z[i] += 1
		t -= 1
	a = 0
	for i in range(n):
		for j in range(z[i]):
			ans[i][a % n] = 1
			a += 1
	a = [0 for i in range(n)]
	b = [0 for i in range(n)]
	for i in range(n):
		for j in range(n):
			a[i] += ans[i][j]
			b[j] += ans[i][j]
			ans[i][j] = str(ans[i][j])
	print(pow(max(a) - min(a), 2) + pow(max(b) - min(b), 2))
	for i in range(n):
		print(''.join(ans[i]))


def solve(n, k):
	r = n * n - k
	res = [None] * n
	for i in range(n):
		res[i] = [1] * n
	diag = (0, 0)
	if r == 0:
		return (0, res)
	ix = -1
	i = 0
	while True:
		for el in get_diag_el(diag, n):
			res[el[0]][el[1]] = 0
			i += 1
			if i >= r:
				return (0 if k % n == 0 else 2, res)
		ix += 1
		pos = 1 if ix % 4 == 0 or ix % 4 == 3 else -1
		if pos == 1:
			shift = ix // 4 + 1 if ix % 4 == 0 else n - (ix + 1) // 4
		else:
			shift = (ix + 2) // 4 if (ix + 2) % 4 == 0 else n - (ix + 3) // 4
		diag = (0, shift) if pos == 1 else (shift, 0)

def get_diag_el(dxdy, n):
	cur = dxdy
	while cur[0] < n and cur[1] < n:
		yield cur
		cur = (cur[0] + 1, cur[1] + 1)
	return
t = int(input())
for i_t in range(t):
	current_str = input().split(' ')
	n = int(current_str[0])
	k = int(current_str[1])
	ret = solve(n, k)
	print(ret[0])
	for i in range(len(ret[1])):
		print(''.join(map(str, ret[1][i])))


t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	every_row = k // n
	rem = k % n
	matrix = [[0 for i in range(n)] for j in range(n)]
	for i in range(n):
		end = every_row
		if rem > 0:
			end += 1
			rem -= 1
		count = 0
		start = i
		while count < end:
			matrix[i][start] = 1
			count += 1
			start = (start + 1) % n
	if k % n >= 1:
		print(2)
	else:
		print(0)
	for i in range(n):
		for j in range(n):
			if j == n - 1:
				print(matrix[i][j])
			else:
				print(matrix[i][j], end='')


def lshift(s, n):
	return s[n:] + s[:n]

def solve_board(side, n_ones):
	fdiv = n_ones // side
	rem = n_ones % side
	initial_x = (fdiv + 1) * '1' + (side - fdiv - 1) * '0'
	initial = fdiv * '1' + (side - fdiv) * '0'
	l1 = [lshift(initial_x, k) for k in range(rem)]
	l2 = [lshift(initial, k) for k in range(rem, side)]
	return (l1 + l2, min(rem, 1) * 2)
t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	(board, co) = solve_board(n, k)
	print(co)
	for line in board:
		print(line)


def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		if k <= n:
			if k == n or k == 0:
				print(0)
			else:
				print(2)
			for ii in range(n):
				s = ''
				for jj in range(n):
					if ii == jj and k > 0:
						s += '1'
						k -= 1
					else:
						s += '0'
				print(s)
			continue
		if k % n == 0:
			print(0)
			diags = k // n
		else:
			print(2)
			diags = k // n + 1
		l = [n - 1]
		for x in range(diags - 1):
			l.append(x)
			l.append(n + x)
		setl = set(l)
		printl = []
		have = 0
		for i in range(n):
			s = []
			for j in range(n):
				if i + j in setl:
					s.append('1')
					have += 1
				else:
					s.append('0')
			printl.append(s)
		have -= k
		current_diag = l.pop()
		cr = n - 1
		cc = current_diag - n + 1
		while have > 0:
			have -= 1
			printl[cr][cc] = '0'
			cr -= 1
			cc += 1
			if cc >= n:
				break
		current_diag = l.pop()
		cr = current_diag
		cc = 0
		while have > 0:
			have -= 1
			printl[cr][cc] = '0'
			cr -= 1
			cc += 1
			if cr < 0:
				break
		for row in printl:
			print(''.join(row))
main()


def fun(n, k, matrix):
	if k == 0:
		return matrix
	for j in range(n):
		for i in range(n - j):
			matrix[i][i + j] = '1'
			k -= 1
			if k == 0:
				return matrix
		for i in range(n - 1 - j, n):
			matrix[i][i - (n - 1 - j)] = '1'
			k -= 1
			if k == 0:
				return matrix
	return matrix
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	matrix = [['0' for i in range(n)] for j in range(n)]
	matrix = fun(n, k, matrix)
	maxR = 0
	minR = 10 ** 6
	maxC = 0
	minC = 10 ** 6
	for i in matrix:
		c = i.count('1')
		maxR = max(maxR, c)
		minR = min(minR, c)
	for i in range(n):
		c = 0
		for j in range(n):
			if matrix[j][i] == '1':
				c += 1
		maxC = max(maxC, c)
		minC = min(minC, c)
	print((maxR - minR) ** 2 + (maxC - minC) ** 2)
	for i in matrix:
		print(''.join(i))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	X = n - 1
	Y = -1
	mat = [[0 for i in range(n)] for j in range(n)]
	f = 0
	while True:
		Y += 1
		for i in range(n):
			if k == 0:
				f = 1
				break
			mat[(X - i + n) % n][(Y + i) % n] = 1
			k -= 1
			if k == 0:
				f = 1
				break
		if f == 1:
			break
	maxa = -1
	mina = 10000000000
	for i in range(n):
		temp = 0
		for j in range(n):
			temp += mat[i][j]
		maxa = max(maxa, temp)
		mina = min(mina, temp)
	print(2 * (maxa - mina) ** 2)
	for i in range(n):
		for j in range(n):
			print(mat[i][j], end='')
		print('')


from sys import *
for _ in range(int(stdin.readline())):
	(n, k) = [int(x) for x in stdin.readline().split()]
	v = [[False for i in range(n)] for j in range(n)]
	col = [0] * n
	line = [0] * n
	for i in range(n):
		if k == 0:
			break
		for j in range(n):
			if k == 0:
				break
			v[(i + j) % n][j] = True
			k -= 1
			col[j] += 1
			line[(i + j) % n] += 1
	sum = 0
	mi = line[0]
	mx = line[0]
	for i in range(n):
		mi = min(mi, line[i])
		mx = max(mx, line[i])
	sum += mx - mi
	mi = col[0]
	mx = col[0]
	for i in range(n):
		mi = min(mi, col[i])
		mx = max(mx, col[i])
	sum += mx - mi
	stdout.write(str(sum) + '\n')
	for i in range(n):
		for j in range(n):
			if v[i][j] == False:
				stdout.write('0')
			else:
				stdout.write('1')
		stdout.write('\n')


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	ans = [[0] * n for i in range(n)]
	id = 0
	while k > 0:
		for i in range(n):
			ans[i][(i + id) % n] = 1
			k -= 1
			if k == 0:
				break
		id += 1
	for i in range(n):
		print(''.join(map(str, ans[i])))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	tempk = k
	arr = [[0] * n for i in range(n)]
	j = 0
	i = 0
	count = 0
	while k > 0:
		count += 1
		arr[i % n][(i + j) % n] = 1
		i += 1
		k -= 1
		if count == n:
			j += 1
			i = 0
			count = 0
	if tempk % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		for j in range(n):
			print(arr[i][j], end='')
		print()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = [[0 for i in range(n)] for j in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	temp = 0
	while True:
		(i, j) = (0, temp)
		for q in range(n):
			if k > 0 and i < n and (j < n):
				arr[i][j] = 1
				i += 1
				j += 1
				k -= 1
			elif k > 0 and j >= n:
				j = 0
				arr[i][j] = 1
				i += 1
				j += 1
				k -= 1
			else:
				break
		else:
			temp += 1
			continue
		break
	for i in arr:
		for j in i:
			print(j, end='')
		print()


import os
import sys
from io import BytesIO, IOBase
import threading
from collections import defaultdict

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		grid = [[0] * n for i in range(n)]
		r_k = k // n
		start = 0
		for i in range(n):
			for j in range(r_k + (1 if i < k % n else 0)):
				grid[i][(start + j) % n] = 1
			start += r_k + (1 if i < k % n else 0)
		cnt1 = [0] * n
		cnt2 = [0] * n
		for i in range(n):
			cnt1[i] = sum(grid[i])
			for j in range(n):
				cnt2[j] += grid[i][j]
		print((max(cnt1) - min(cnt1)) ** 2 + (max(cnt2) - min(cnt2)) ** 2)
		for i in range(n):
			print(''.join([str(j) for j in grid[i]]))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = [[0 for j in range(n)] for i in range(n)]
	j = 0
	if k == 0:
		print(0)
		for i in range(0, n):
			for j in range(0, n):
				print(0, end='')
			print()
		continue
	count = [0] * n
	if k % n == 0:
		(b, j) = (k // n, n - 1)
		for i in range(0, n):
			a = j - b + 1
			if a < 0:
				a = a % n
				for m in range(a, n):
					l[i][m] = 1
					count[m] += 1
				for m in range(0, j + 1):
					l[i][m] = 1
					count[m] += 1
			else:
				for m in range(a, j + 1):
					l[i][m] = 1
					count[m] += 1
			j -= 1
	else:
		(b, ct, fg, j) = (k // n + 1, k % n, 0, n - 1)
		for i in range(0, n):
			if i >= ct and fg == 0:
				b -= 1
				fg = 1
			a = j - b + 1
			if a < 0:
				a = a % n
				for m in range(a, n):
					l[i][m] = 1
					count[m] += 1
				for m in range(0, j + 1):
					l[i][m] = 1
					count[m] += 1
			else:
				for m in range(a, j + 1):
					l[i][m] = 1
					count[m] += 1
			j -= 1
	(mxr, mxc, mir, mic) = (-1, -1, 1000, 1000)
	for i in range(0, n):
		a = l[i].count(1)
		mir = min(mir, a)
		mxr = max(mxr, a)
	mic = min(count)
	mxc = max(count)
	f = (mxr - mir) ** 2 + (mxc - mic) ** 2
	print(f)
	for i in range(0, n):
		for j in range(0, n):
			print(l[i][j], end='')
		print()


t = int(input())
for hatt in range(t):
	lis = input().split()
	(n, k) = (int(lis[0]), int(lis[1]))
	num1 = k // n
	if k % n != 0:
		num1 += 1
	numn = num1 * n - k
	arr = [['0' for j in range(n)] for i in range(n)]
	for i in range(n):
		start = i
		for c in range(num1):
			arr[i][start] = '1'
			if start == n - 1:
				start = 0
			else:
				start += 1
	for i in range(numn):
		arr[i][i] = '0'
	if k % n == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		print(''.join(arr[i]))


t = int(input())
for _ in range(t):
	(n, k) = [int(i) for i in input().split()]
	if k % n == 0:
		print(0)
	else:
		print(2)
	r = k % n
	s = k // n + 1
	for i in range(n):
		if r == 0:
			s -= 1
		if i + s > n:
			print('1' * (i + s - n) + '0' * (n - s) + '1' * (n - i))
		else:
			print('0' * i + '1' * s + '0' * (n - s - i))
		r -= 1


import os, io
from sys import stdout
import collections
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from collections import Counter

def primes(n):
	sieve = [True] * n
	for i in range(3, int(n ** 0.5) + 1, 2):
		if sieve[i]:
			sieve[i * i::2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
	return [2] + [i for i in range(3, n, 2) if sieve[i]]

def binomial_coefficient(n, k):
	if 0 <= k <= n:
		ntok = 1
		ktok = 1
		for t in range(1, min(k, n - k) + 1):
			ntok *= n
			ktok *= t
			n -= 1
		return ntok // ktok
	else:
		return 0

def powerOfK(k, max):
	if k == 1:
		return [1]
	if k == -1:
		return [-1, 1]
	result = []
	n = 1
	while n <= max:
		result.append(n)
		n *= k
	return result

def prefixSum(arr):
	for i in range(1, len(arr)):
		arr[i] = arr[i] + arr[i - 1]
	return arr

def divisors(n):
	i = 1
	result = []
	while i * i <= n:
		if n % i == 0:
			if n / i == i:
				result.append(i)
			else:
				result.append(i)
				result.append(n / i)
		i += 1
	return result

def kadane(a, size):
	max_so_far = 0
	max_ending_here = 0
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def digitsSum(n):
	if n == 0:
		return 0
	r = 0
	while n > 0:
		r += n % 10
		n //= 10
	return r
t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	grid = []
	for i in range(n):
		grid.append([0] * n)
	if k % n == 0:
		print(0)
	else:
		print(2)
	while k > 0:
		for i in range(n):
			(a, b) = (i + 0, 0)
			for z in range(n):
				grid[b % n][a % n] = 1
				a += 1
				b += 1
				k -= 1
				if k == 0:
					break
			if k == 0:
				break
	for l in grid:
		print(''.join([str(e) for e in l]))


import os
import sys
from io import BytesIO, IOBase

def main():
	T = int(input())
	while T:
		T = T - 1
		(n, k) = map(int, input().split())
		li = [0 for i in range(0, n)]
		li = [li.copy() for i in range(0, n)]
		co = 0
		for i in range(0, n):
			if co < k:
				for j in range(0, n):
					if co < k:
						li[(i + j) % n][j] = 1
						co = co + 1
					else:
						break
		maxR = 0
		minR = n + 1
		maxC = 0
		minC = n + 1
		co = 0
		for i in li:
			maxR = max(i.count(1), maxR)
			minR = min(i.count(1), minR)
		for i in range(0, n):
			co = 0
			for j in range(0, n):
				co = co + li[j][i]
			maxC = max(maxC, co)
			minC = min(minC, co)
		print((maxR - minR) ** 2 + (maxC - minC) ** 2)
		for i in li:
			print(*i, sep='')
main()


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
from collections import defaultdict
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for t in range(int(input())):
	(n, k) = map(int, input().split())
	r = k // n
	s = '1' * r + '0' * (n - r)
	a = [['' for i in range(n)] for j in range(n)]
	for i in range(n):
		for j in range(n):
			a[i][j] = s[j]
		s = s[1:] + s[0]
	rem = k % n
	cols = [0] * n
	for i in range(n):
		for j in range(n):
			if a[i][j] == '0' and cols[j] == 0:
				if rem > 0:
					a[i][j] = '1'
					rem -= 1
					cols[j] += 1
				break
		if rem <= 0:
			break
	c = 0
	if k % n != 0:
		c = 1
	res = 2 * (c * c)
	print(res)
	for i in range(n):
		print(*a[i], sep='')


from sys import stdin, stdout
import heapq
import cProfile
from collections import Counter, defaultdict, deque
from functools import reduce
import math
from bisect import bisect, bisect_right, bisect_left

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def solve():
	(n, k) = get_tuple()
	arr = [[0 for _ in range(n)] for _ in range(n)]
	(i, j) = (0, 0)
	sj = 0
	while k > 0:
		k -= 1
		arr[i][j] = 1
		i = (i + 1) % n
		if i == 0:
			sj += 1
			j = sj
		else:
			j = (j + 1) % n
	colsum = [0] * n
	rowsum = [0] * n
	for i in range(n):
		for j in range(n):
			colsum[j] += arr[i][j]
			rowsum[i] += arr[i][j]
	ans = (max(rowsum) - min(rowsum)) ** 2 + (max(colsum) - min(colsum)) ** 2
	print(ans)
	for val in arr:
		print(''.join([str(e) for e in val]))

def main():
	solve()
TestCases = True
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


import sys
import math
strInp = lambda : input().strip().split()
intInp = lambda : list(map(int, strInp()))
for t in range(int(input())):
	(n, k) = intInp()
	if k == 0:
		print(0)
		for i in range(n):
			for j in range(n):
				print('0', end='')
			print()
	else:
		if k % n == 0:
			print(0)
		else:
			print(2)
		ans = []
		for i in range(n):
			ans.append(['0'] * n)
		i = 0
		j = 0
		circle = 0
		while k > 0:
			ans[i][j] = '1'
			i += 1
			j += 1
			circle += 1
			if i == n:
				i = 0
			if j == n:
				j = 0
			if circle % n == 0:
				j = circle // n
			k -= 1
		for i in range(n):
			for j in range(n):
				print(ans[i][j], end='')
			print()


import math
from sys import stdin
from collections import Counter, defaultdict, deque
input = stdin.readline
mod = pow(10, 9) + 7

def solve():
	(n, k) = map(int, input().split())
	if 1:
		l1 = [[0 for i in range(n)] for j in range(n)]
		c = 0
		x1 = math.ceil(k / n)
		x2 = math.floor(k / n)
		c = 2 * ((x1 - x2) * (x1 - x2))
		print(c)
		n1 = n
		for i in range(n):
			x1 = math.ceil(k / n1)
			k = k - x1
			c2 = i
			for j in range(n):
				if x1 > 0:
					x1 = x1 - 1
					l1[i][c2 % n] = 1
					c2 = c2 + 1
			n1 = n1 - 1
		for i in range(n):
			for j in range(n):
				print(l1[i][j], end='')
			print()
for _ in range(int(input())):
	solve()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	ans = []
	for i in range(n):
		tem = []
		for j in range(n):
			tem.append(0)
		ans.append(tem)
	i = 0
	j = 0
	main = 0
	if k % n == 0:
		main = 0
	else:
		main = 2
	for ii in range(k):
		ans[i][j] = 1
		i += 1
		j = (j + 1) % n
		if i == n:
			i = 0
			j = (j + 1) % n
	print(main)
	for i in ans:
		for j in i:
			print(j, end='')
		print()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = list()
	for i in range(n):
		mat.append([0] * n)
	if k % n == 0:
		print(0)
	else:
		print(2)
	p = q = 0
	while k > 0:
		k -= 1
		mat[p][q] = 1
		p += 1
		q += 1
		q %= n
		if p == n:
			p = 0
			q += 1
			q %= n
	for i in range(n):
		print(*mat[i], sep='')


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [['0'] * n for i in range(n)]
	for i in range(n):
		if k == 0:
			break
		for j in range(n):
			if k == 0:
				break
			mat[(i + j) % n][j] = '1'
			k -= 1
	c = [0] * n
	r = [0] * n
	for i in range(n):
		for j in range(n):
			r[i] += int(mat[i][j])
			c[j] += int(mat[i][j])
	print((max(c) - min(c)) ** 2 + (max(r) - min(r)) ** 2)
	for i in mat:
		print(''.join(i))


t = int(input())
for t_ in range(t):
	(n, k) = map(int, input().split())
	x = int(k / n)
	r = k - n * x
	if r == 0:
		print(0)
		k = 0
		for n_ in range(n):
			if k + x <= n:
				row = '0' * k + '1' * x + '0' * (n - k - x)
			if k + x > n:
				row = '1' * (k + x - n) + '0' * (n - x) + '1' * (n - k)
			print(row)
			k += x
			if k > n:
				k -= n
	else:
		print(2)
		x += 1
		k = 0
		for n_ in range(n):
			if k + x <= n:
				row = '0' * k + '1' * x + '0' * (n - k - x)
			if k + x > n:
				row = '1' * (k + x - n) + '0' * (n - x) + '1' * (n - k)
			print(row)
			k += x
			if k > n:
				k -= n
			r -= 1
			if r == 0:
				x -= 1


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0] * n for i in range(n)]
	(row, col) = (0, -1)
	for i in range(k):
		if not i % n:
			col += 1
		mat[row % n][col % n] = 1
		row += 1
		col += 1
	print(2 if k % n else 0)
	for i in mat:
		print(*i, sep='')


T = int(input())
while T > 0:
	(n, k) = map(int, input().split())
	every_row = k // n
	plus = 0
	if k % n != 0:
		plus = k % n
	if plus != 0:
		print(2)
	else:
		print(0)
	if every_row == n:
		temp = ['1'] * n
	else:
		temp = ['1'] * (every_row + 1) + ['0'] * (n - every_row - 1)
		index = every_row
		for i in range(plus):
			print(''.join(temp))
			x = temp[0]
			temp.pop(0)
			if x == '1':
				temp.append('1')
			else:
				temp.append('0')
			index -= 1
			if index < 0:
				index = n - 1
		temp[index] = '0'
	for i in range(n - plus):
		print(''.join(temp))
		x = temp[0]
		temp.pop(0)
		if x == '1':
			temp.append('1')
		else:
			temp.append('0')
	T -= 1


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	grid = [[0 for i in range(n)] for j in range(n)]
	b = k // n
	total = k % n
	ok = True
	m = 0
	for i in range(n):
		for j in range(b):
			grid[i][m % n] = 1
			m += 1
		if total > 0:
			grid[i][m % n] = 1
			m += 1
			total -= 1
	minR = 301
	maxR = -1
	for i in grid:
		p = sum(i)
		if p < minR:
			minR = p
		if p > maxR:
			maxR = p
	minC = 301
	maxC = -1
	for i in range(n):
		p = sum((grid[j][i] for j in range(n)))
		if p < minC:
			minC = p
		if p > maxC:
			maxC = p
	print((maxR - minR) ** 2 + (maxC - minC) ** 2)
	for i in grid:
		print(''.join((str(j) for j in i)))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = []
	for i in range(n):
		a.append([0] * n)
	p = 0
	q = 0
	for i in range(k):
		a[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for ele in a:
		print(*ele, sep='')


import sys
t = int(input())
for ii in range(t):
	(n, k) = map(int, input().split())
	mat = [[0] * n for _ in range(n)]
	o = k // n
	m = k - o * n
	cur = 0
	for i in range(n):
		cur = i
		if i < m:
			for j in range(o + 1):
				mat[i][cur] = 1
				cur = (cur + 1) % n
		else:
			for j in range(o):
				mat[i][cur] = 1
				cur = (cur + 1) % n
	if m == 0:
		print(0)
	else:
		print(2)
	for i in mat:
		print(''.join(map(str, i)))


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []

def fill_diagonal(starting_pt, amt):
	global n
	dx = -1
	dy = +1
	(i, j) = starting_pt
	while j < n and i >= 0 and (amt > 0):
		grid[i][j] = 1
		i += dx
		j += dy
		amt -= 1
	return amt
for _ in range(testCases):
	(n, k) = input_split()
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	grid = [[0 for j in range(n)] for i in range(n)]
	amt = k
	for i in range(n - 1, -1, -1):
		amt = fill_diagonal((i, 0), amt)
		amt = fill_diagonal((n - 1, i), amt)
		if amt == 0:
			break
	print(ans)
	for i in range(n):
		print(''.join([str(el) for el in grid[i]]))
print(*answers, sep='\n')


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	mat = [['0'] * n for i in range(n)]
	i = 0
	j = 0
	while k:
		mat[i % n][j % n] = '1'
		i += 1
		j += 1 + int(i % n == 0)
		k -= 1
	for x in mat:
		print(''.join(x))


t = int(input())
while t:
	l1 = [int(x) for x in input().split()]
	if l1[1] == 0 or l1[1] == l1[0] or (l1[1] > l1[0] and (l1[1] - l1[0]) % l1[0] == 0):
		print(0)
	else:
		print(2)
	hess = [[0 for x in range(l1[0])] for x in range(l1[0])]
	i = 0
	i = 0
	while i < len(hess):
		cell = hess[i]
		j = 0
		while j < len(cell):
			starter = i
			targ = i
			while targ < l1[1]:
				cell[(starter + j) % l1[0]] = 1
				j += 1
				targ += l1[0]
			print(''.join([str(x) for x in cell]))
			break
		i += 1
	t -= 1


def testcase():
	import sys
	input = sys.stdin.readline
	(n, k) = [int(x) for x in input().strip().split()]
	if k % n == 0:
		print(0)
	else:
		print(2)
	ones = (k + n - 1) // n
	l = ['1'] * ones + ['0'] * (n - ones)
	m = k % n
	for i in range(n):
		print(''.join(l))
		l = [l[-1]] + l[:-1]
		if i + 1 == m:
			l[(i + k // n + 1) % n] = '0'

def main():
	import sys
	input = sys.stdin.readline
	t = int(input())
	for _ in range(t):
		testcase()
main()


o = int(input())
for _ in range(o):
	(n, k) = map(int, input().split(' '))
	A = [[0 for i in range(n)] for i in range(n)]
	if k % n == 0:
		ans = 0
	else:
		ans = 2
	row = [k // n for i in range(n)]
	for i in range(k % n):
		row[i] += 1
	for i in range(n):
		col = i
		for j in range(row[i]):
			temp = (col + j) % n
			A[i][temp] = 1
	print(ans)
	for i in A:
		for j in i:
			print(j, end='')
		print()


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for _ in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def f(A):
	R = [sum(row) for row in A]
	fR = pow(min(R) - max(R), 2)
	C = []
	for i in range(len(A)):
		s = 0
		for j in range(len(A)):
			s += A[j][i]
		C.append(s)
	fC = pow(min(C) - max(C), 2)
	return fR + fC

def solve(n, k):
	A = [[0] * n for _ in range(n)]
	count = 0
	for i in range(n):
		for j in range(n):
			if count == k:
				return (f(A), A)
			A[j][(i + j) % n] = 1
			count += 1
	return (f(A), A)
for _ in tests():
	(n, k) = arr_in()
	(val, matrix) = solve(n, k)
	out(val)
	for row in matrix:
		out(''.join(map(str, row)))


def findGrid(d):
	n = d[0]
	k = d[1]
	p = 0
	q = 0
	grid = [[0 for i in range(d[0])] for j in range(d[0])]
	for i in range(k):
		grid[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	r = [0, d[1]]
	c = [0, d[1]]
	temp = 0
	temp1 = 0
	j0 = 0
	for i in range(d[0]):
		temp1 = 0
		temp = 0
		for j in range(d[0]):
			temp1 += grid[i][j]
			temp += grid[j][j0]
		j0 += 1
		if r[0] < temp1:
			r[0] = temp1
		if r[1] > temp1:
			r[1] = temp1
		if c[0] < temp:
			c[0] = temp
		if c[1] > temp:
			c[1] = temp
	rr = []
	rr.append((r[0] - r[1]) ** 2 + (c[0] - c[1]) ** 2)
	rr.append(grid)
	return rr
r = []
t = int(input())
for i in range(t):
	data = input().split(' ')
	r.append(findGrid([int(data[0]), int(data[1])]))
for i in r:
	print(i[0])
	x = i[1]
	for j in x:
		for y in j:
			print(y, end='')
		print()


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [['0' for __ in range(n)] for _ in range(n)]
	i = 0
	j = 0
	for q in range(k):
		mat[i][j] = '1'
		i += 1
		j = (j + 1) % n
		if i == n:
			i = 0
			j = (j + 1) % n
	if k % n == 0:
		print(0)
	else:
		print(2)
	for _ in range(n):
		print(''.join(mat[_]))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = k // n
	b = k % n
	if b == 0:
		print(0)
	else:
		print(2)
	ans = [[0] * n for _ in range(n)]
	for i in range(n):
		for j in range(a + int(b > 0)):
			mod = (i + j) % n
			ans[i][mod] = 1
		if b != 0:
			b -= 1
	for i in range(n):
		for j in range(n):
			ans[i][j] = str(ans[i][j])
	for x in ans:
		print(''.join(x))


input = __import__('sys').stdin.readline

def matrix(n, k):
	i = j = l = m = l = 0
	while k != 0:
		for i in range(n):
			m = 0
			l = i
			while k > 0 and l != n:
				mat[m][l] = 1
				k -= 1
				m += 1
				l += 1
			if k == 0:
				break
			j = n - i
			m = 0
			while k > 0 and j < n:
				mat[j][m] = 1
				k -= 1
				j += 1
				m += 1
			if k == 0:
				break
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	mat = [[0] * n for i in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	matrix(n, k)
	for i in mat:
		print(*i, sep='')


import os
import sys
from io import BytesIO, IOBase

def main():
	T = int(input())
	while T:
		T = T - 1
		(n, k) = map(int, input().split())
		li = [0 for i in range(0, n)]
		li = [li.copy() for i in range(0, n)]
		co = 0
		for i in range(0, n):
			if co < k:
				for j in range(0, n):
					if co < k:
						li[(i + j) % n][j] = 1
						co = co + 1
					else:
						break
		maxR = 0
		minR = n + 1
		maxC = 0
		minC = n + 1
		co = 0
		for i in li:
			maxR = max(i.count(1), maxR)
			minR = min(i.count(1), minR)
		for i in range(0, n):
			co = 0
			for j in range(0, n):
				co = co + li[j][i]
			maxC = max(maxC, co)
			minC = min(minC, co)
		print((maxR - minR) ** 2 + (maxC - minC) ** 2)
		for i in li:
			print(*i, sep='')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	if k % n == 0:
		print(0)
		a = k // n
		b = []
		for i in range(n):
			b.append(['0'] * n)
		for i in range(n):
			for j in range(a):
				b[i][(i + j) % n] = '1'
		for i in range(n):
			print(''.join(b[i]))
	else:
		print(2)
		a = k // n
		c = k % n
		b = []
		for i in range(n):
			b.append(['0'] * n)
		for i in range(n):
			for j in range(a):
				b[i][(i + j) % n] = '1'
		d = b[0].index('0')
		e = 0
		f = 0
		for i in range(c):
			b[e % n][(d - f) % n] = '1'
			e += 1
			f -= 1
		for i in range(n):
			print(''.join(b[i]))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	each = k // n
	rem = k % n
	if rem == 0:
		print(0)
	else:
		print(2)
	for i in range(n):
		arr = [0] * n
		for j in range(i, i + each):
			arr[j % n] = 1
		if i < rem:
			arr[(i + each) % n] = 1
		for x in arr:
			print(x, end='')
		print('')


t = int(input())
for T in range(t):
	(n, k) = [int(x) for x in input().split()]
	ans = [['0' for i in range(n)] for j in range(n)]
	if k % n == 0:
		print(0)
	else:
		print(2)
	(ind1, ind2) = (0, 0)
	while ind1 < k:
		(i, j) = (0, ind2)
		while i < n and ind1 < k:
			ans[i][j] = '1'
			ind1 += 1
			i += 1
			j = (j + 1) % n
		ind2 += 1
	for j in ans:
		print(''.join(j))


t = int(input())
for x in range(t):
	(n, k) = map(int, input().split())
	if k % n == 0:
		f = 0
	else:
		f = 2
	print(f)
	e = k % n
	no = k // n
	c = 1
	s = ''
	ss = ''
	oc = 0
	for i in range(n):
		if no != 0:
			s += '1'
			ss += '1'
			no -= 1
		elif e != 0 and oc == 0:
			s += '1'
			ss += '0'
			oc = 1
		else:
			ss += '0'
			s += '0'
	for i in range(n):
		if e != 0:
			print(s)
			e -= 1
		else:
			print(ss)
		s = s[c:] + s[:c]
		ss = ss[c:] + ss[:c]


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7
for _ in range(I()):
	(n, k) = R()
	p = k // n
	r = k % n
	print(0 if not r else 2)
	for i in range(n):
		c = 0
		if i < r:
			c = 1
		a = ['0'] * n
		for j in range(i, min(n, i + p + c)):
			a[j] = '1'
		for j in range(0, max(0, i + p + c - n)):
			a[j] = '1'
		print(*a, sep='')


import sys
input = sys.stdin.readline
Q = int(input())
Query = [list(map(int, input().split())) for _ in range(Q)]
for (N, K) in Query:
	state = [[0] * N for _ in range(N)]
	if K % N == 0:
		print(0)
		h1 = K // N
		for i in range(h1):
			for r in range(N):
				state[r][(r + i) % N] = 1
		for i in range(h1, N):
			for r in range(N):
				state[r][(r + i) % N] = 0
	else:
		print(2)
		h1 = K // N
		am = K % N
		for k in range(N):
			state[k][k] = 1 if k < am else 0
		for i in range(1, h1 + 1):
			for r in range(N):
				state[r][(r + i) % N] = 1
		for i in range(h1 + 1, N):
			for r in range(N):
				state[r][(r + i) % N] = 0
	for s in state:
		print(*s, sep='')


import bisect
import os
import gc
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		(n, k) = ain()
		if n ** 2 == k:
			print(0)
			s = '1' * n
			for i in range(n):
				print(s)
		elif k == 0:
			print(0)
			s = '0' * n
			for i in range(n):
				print(s)
		else:
			rv = 0
			cv = 0
			if k % n == 0:
				print(0)
				s = '1' * (k // n) + '0' * (n - k // n)
				for i in range(n):
					print(s)
					s = s[-1] + s[0:n - 1]
			else:
				print(2)
				x = math.ceil(k / n)
				s = '1' * x + '0' * (n - x)
				tmp = -1
				for i in range(k % n):
					tmp = i
					print(s)
					s = s[-1] + s[0:n - 1]
				l = ['0'] * n
				for i in range(x - 1):
					l[(tmp + 1 + i) % n] = '1'
				s = ''.join(l)
				for i in range(n - k % n):
					print(s)
					s = s[-1] + s[0:n - 1]
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	matrix = []
	for i in range(n):
		row = [0] * n
		matrix.append(row)
	if k % n == 0:
		print(0)
	else:
		print(2)
	init = 1
	i = 0
	j = 0
	while k > 0:
		matrix[i][j] = 1
		if i == n - 1:
			i = 0
			j = init
			init += 1
		else:
			i = (i + 1) % n
			j = (j + 1) % n
		k -= 1
	for i in range(n):
		for j in range(n):
			print(matrix[i][j], end='')
		print()


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math, datetime, functools, itertools, operator, bisect, fractions, statistics
from collections import deque, defaultdict, OrderedDict, Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify, _heapify_max, _heappop_max

def main():
	starttime = datetime.datetime.now()
	if os.path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	tc = ri()
	for _ in range(tc):
		(n, k) = ria()
		R = {}
		C = {}
		a = []
		for i in range(n):
			a.append([0] * n)
			R[i] = 0
			C[i] = 0
		n1us = {}
		no = 0
		c = 0
		(ix, iy) = (0, 0)
		for i in range(n):
			if no == k:
				break
			a[(ix + i) % n][(iy + i) % n] = 1
			R[(ix + i) % n] += 1
			C[(iy + i) % n] += 1
			no += 1
			if no == k:
				break
		if no < k:
			while True:
				c += 1
				(ix, iy) = (c, 0)
				for i in range(n):
					a[(ix + i) % n][(iy + i) % n] = 1
					R[(ix + i) % n] += 1
					C[(iy + i) % n] += 1
					no += 1
					if no == k:
						break
				if no == k:
					break
		maxr = 0
		minr = 9999999999999999999999
		maxc = 0
		minc = 9999999999999999999999
		for i in R:
			maxr = max(maxr, R[i])
			minr = min(minr, R[i])
		for i in C:
			maxc = max(maxc, C[i])
			minc = min(minc, C[i])
		print((maxr - minr) ** 2 + (maxc - minc) ** 2)
		for i in a:
			s = ''
			for j in i:
				s += str(j)
			print(s)
	endtime = datetime.datetime.now()
	time = (endtime - starttime).total_seconds() * 1000
	if os.path.exists('input.txt'):
		print('Time:', time, 'ms')

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


for test in range(int(input())):
	(n, k) = map(int, input().split())
	if k % n == 0:
		print(0)
	else:
		print(2)
	p = 0
	q = 0
	a = [[0 for i in range(n)] for j in range(n)]
	for i in range(k):
		a[p][q] = 1
		p += 1
		q = (q + 1) % n
		if p == n:
			p = 0
			q = (q + 1) % n
	for i in range(n):
		for j in range(n):
			print(a[i][j], end='')
		print()


def main():
	t = Iint()
	for _ in range(t):
		(n, k) = Imap()
		a = [[0 for i in range(n)] for j in range(n)]
		space = k // n
		rem = k % n
		if rem == 0:
			print(0)
		else:
			print(2)
		for row in range(n):
			start = row
			i = start - 1
			for i in range(start, start + space):
				a[row][i % n] = 1
			if rem:
				a[row][(i + 1) % n] = 1
				rem -= 1
			Plist(a[row], '')
FIO = 10

def I():
	return input()

def Iint():
	return int(input())

def Ilist():
	return list(map(int, input().split()))

def Imap():
	return map(int, input().split())

def Plist(li, s=' '):
	print(s.join(map(str, li)))
en = enumerate
if not FIO:
	if __name__ == '__main__':
		main()
		exit()
else:
	from io import BytesIO, IOBase
	import sys
	import os
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
main()


def grid(n, k):
	(q, r) = (k // n, k % n)
	if r:
		print(2)
	else:
		print(0)
	for i in range(r):
		row = ['0' for j in range(n)]
		for j in range(q + 1):
			row[(i + j) % n] = '1'
		print(''.join(row))
	for i in range(r, n):
		row = ['0' for j in range(n)]
		for j in range(q):
			row[(i + j) % n] = '1'
		print(''.join(row))
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	grid(n, k)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	(n, k) = value()
	each = k // n
	ans = [[0 for i in range(n)] for j in range(n)]
	extra = k % n
	start = -1
	for i in range(n):
		start += 1
		for j in range(start, start + each):
			ans[i][j % n] = 1
		if extra:
			ans[i][(start + each) % n] = 1
			extra -= 1
	c = 0
	if k % n:
		c = 2
	print(c)
	for i in ans:
		print(*i, sep='')