Skip to content

Instantly share code, notes, and snippets.

@keturiosakys
Created July 3, 2023 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keturiosakys/82373aef4cc0ecfb156bf57a80b81195 to your computer and use it in GitHub Desktop.
Save keturiosakys/82373aef4cc0ecfb156bf57a80b81195 to your computer and use it in GitHub Desktop.
Given an integer n, return true if it's a perfect square AND when reversed, is still a perfect square.
open Base
open Stdlib
let reversed_squares num =
let perfect_root n =
let n = float_of_int n in
let root = Float.sqrt n in
if root |> int_of_float |> float_of_int = root then Some root else None
in
let int_reverse n =
let rec reverser rem acc =
match n = n % rem with
| true ->
(n % rem / (rem / 10)) :: acc
|> List.rev
|> List.fold_left (fun acc dig -> (acc * 10) + dig) 0
| false -> reverser (rem * 10) ((n % rem / (rem / 10)) :: acc)
in
reverser 10 []
in
let rev_num = int_reverse num in
match (perfect_root num, perfect_root rev_num) with
| Some _, Some _ -> true
| _ -> false
let%test_module "reversed squares" =
(module struct
let%test_unit "test 1" = [%test_eq: bool] (reversed_squares 9) true
let%test_unit "test 2" = [%test_eq: bool] (reversed_squares 441) true
let%test_unit "test 3" = [%test_eq: bool] (reversed_squares 25) false
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment