Setup
For this challenge, implement a function that will return true
if a number is Automorphic. Automorphics are numbers whose square ends in the same digits as the number itself. The number will always be positive.
Examples
autoMorphic(13)
=> false
13 squared is 69. Since 69 does not end in 13, return false
.
autoMorphic(25)
=> true
25 squared is 625. Since 625 ends in 25, return true
.
Tests
autoMorphic(6)
autoMorphic(625)
autoMorphic(225)
Good luck!~
This challenge comes from MrZizoScream on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (21)
Here is some crappy Java Solution
Here is the output
Solution without strings (Haskell)
An explanation: if n² ends in n, then n² - n ends in as many zeroes as there are digits in n. I'm not going to prove this here, I believe it is pretty straightforward. If a number ends in m zeroes, then the number is divisible (remainder of 0) by 10m.
The test now is: is n² - n divisible by 10 ^ (number of digits in n). Finding the number of digits is simple: the log base 10 of a number with m digits is m - x, x is in the interval (0,1]. This translates to floor(log base 10 of n) + 1 = number of digits.
So that's my solution.
Elm
dart
Python
More tests:
11 should be false?
11 * 11 is 121, which ends in 1 hence return True.
oops - i interpreted the problem incorrectly as only the one’s digits needing to match.
No regex for this one :(
Ruby
and Haskell:
JavaScript
I think this should do it in JavaScript:
include
int main()
{
int a , b , q , s=0 ,i=0 , r;
printf("enter the number");
scanf("%d" , &a);
b=a*a;
q=a;
// calculating number of digits in a //
//finding last two digits of b in reverse order //
for(i;i>0;i--)
{
r=q%10;
s=s*10+r;
q=q/10;
}
q=s;
s=0;
//finding digits in correct order //
// now comparing with input //
}
This is the solution in c.
steps :-
1 . ask for a input.
2 . calculate and store the square in another variable.
3 . calculate the number of digits in the input.
4 . find the last two digit of square number .
5 . compare the last two digit number with the input number and give the result.
output :