t = Integer(gets)
while t > 0
a4 = []
a7 = []
n = Integer(gets)
i = 1

while i <= n 
a4 << i.to_s.count("4")
a7 << i.to_s.count("7")

i = i + 1
end
count = 0 
i = 1
while (a4[i] == a7[i] && i<=n)
i =i + 1
end
count = i*(i-1)/2
print "#{count}\n" 
t = t - 1
end