Square Square
April 10, 2018
Here’s my solution in Scheme; other programming languages will allow much shorter solutions:
> (do ((n (+ 3163 1) (+ n 1))) ((= n 10000)) (when (= (modulo (* n n) 10000) n) (display n) (newline))) 9376
You can run the program at https://ideone.com/yqQvh5.
Perl being the true golfing language!
[sourcecode]
perl -E’say grep{$_**2=~/$_$/}1000..9999′
[/sourecode]
Perl being the true golfing language! – just realised 2 bytes too long!
Python 3
87909376 9376
Julia implementation (comprehensive & extensible version):
ContainsOriginal(x::Int64, X::Int64) = string(x) == string(X)[end-3:end]
for x = 1001:9999
if ContainsOriginal(x, x^2); println(x); break; end
end
result: 9376 (after about 0.001 sec, with about 42K memory allocations)
Here’s a version in Basic that is well-suited to that language:
10 PRINT 87909376
Klong version
Mumps version
9376
Hats off 2 Perl. Your golfing skills are beyond compare!
Here’s a Haskell version in the ghci REPL. Not much golfing; only the removal of spaces.
Didn’t we do something like this recently? https://programmingpraxis.com/2016/06/28/curious-numbers/
Anyway, here’s an anti-golf solution to the present problem, using TensorFlow (I’m just learning so this might be a terrible way to solve the problem):
Python 3 version in 46 characters:
[x for x in range(1000,10000) if x*x%10000==x]
Add `[0]’ for 49 characters if it needs to return an int instead of a list.
Python 3:
I see some people have found the solution by finding the modulus with 10**4, thats probably more efficient than what I did, I found the last 4 digs of the square by converting to a list and indexing.
for i in range(103, 104):
sqr = list(str(int(i**2)))
lis = list(str(i))
if lis[:] == sqr[len(sqr) – 4:len(sqr)]:
print(lis[:])
For the range I meant 103, 104, it changed it for some reason and made it bold.
ugh, I mean 10 ^ 3, 10 ^ 4
Here’s a solution in Python. It uses depth-first-search to incrementally construct a valid 4-digit number.
Output:
((1000 to: 9999) select: [:x | x*x\10000 = x]) first “Smalltalk”
I typed x*x\10000 with two backslashes, honest.
Bash
ClojureScript