login
Distance from n to nearest square.
20

%I #34 Nov 16 2022 09:34:40

%S 0,0,1,1,0,1,2,2,1,0,1,2,3,3,2,1,0,1,2,3,4,4,3,2,1,0,1,2,3,4,5,5,4,3,

%T 2,1,0,1,2,3,4,5,6,6,5,4,3,2,1,0,1,2,3,4,5,6,7,7,6,5,4,3,2,1,0,1,2,3,

%U 4,5,6,7,8,8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8,9,9,8,7,6,5,4,3,2,1,0,1,2,3,4

%N Distance from n to nearest square.

%H Reinhard Zumkeller, <a href="/A053188/b053188.txt">Table of n, a(n) for n = 0..10000</a>

%H <a href="/index/Di#distance_to_the_nearest">Index entries for sequences related to distance to nearest element of some set</a>

%F a(n) = |floor(sqrt(n) + 1/2)^2 - n|. - _Ridouane Oudra_, May 01 2019

%F a(n) <= sqrt(n). - _Charles R Greathouse IV_, Nov 16 2022

%e a(7)=2 since 9 is the closest square to 7 and |9-7| = 2.

%t Flatten[Table[Abs[Nearest[Range[0,25]^2,n]-n],{n,0,120}]] (* _Harvey P. Dale_, Mar 14 2011 *)

%o (Haskell)

%o a053188 0 = 0

%o a053188 n = min (n - last xs) (head ys - n) where

%o (xs,ys) = span (< n) a000290_list

%o -- _Reinhard Zumkeller_, Nov 28 2011

%o (Python)

%o from math import isqrt

%o def A053188(n): return abs(((m:=isqrt(n))+int(n-m*(m+1)>=1))**2-n) # _Chai Wah Wu_, Aug 03 2022

%o (PARI) a(n)=abs(((sqrtint(4*n) + 1)\2)^2 - n) \\ _Charles R Greathouse IV_, Nov 16 2022

%Y Cf. A053187, A074989, A000290.

%K easy,nonn

%O 0,7

%A _Henry Bottomley_, Mar 01 2000