How to resolve the algorithm Kaprekar numbers step by step in the F# programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Kaprekar numbers step by step in the F# programming language

Table of Contents

Problem Statement

A positive integer is a Kaprekar number if: Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.

10000 (1002) splitting from left to right:

Generate and show all Kaprekar numbers less than 10,000.

Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.

The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too.

For this purpose, do the following:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Kaprekar numbers step by step in the F# programming language

Source code in the fsharp programming language

// Count digits in number
let digits x =
    let rec digits' p x =
        if 10.**p > x then p else digits' (p + 1.) x
    digits' 1. x


// Is n a Kaprekar number?
let isKaprekar n =
    // Reference: http://oeis.org/A006886
    // Positive numbers n such that n=q+r
    // And n^2=q*10^m+r,
    //  for some m >= 1,
    //  q>=0 and 0<=r<10^m,
    //  with n != 10^a, a>=1.
    let nSquared = n * n
    let a = float((digits n) - 1.)

    // Create a list of tuples from the nSquared digit splits
    [1. .. float (digits nSquared)]
    |> List.map (fun e ->
        // Splits the nSquared digits into 2 parts
        let x = 10.**e
        let q = float(int(Math.Floor (nSquared / x)))
        let r = nSquared - (q * x)
        (q, r))
    // Filter results based on rules
    |> List.exists (fun (q, r) ->
        q + r = n &&
        if a >= 1. then n % 10.**a <> 0. else true)


// List Kaprekar numbers from 1 to 10,000
[1 .. 10000]
|> List.filter (float >> isKaprekar)

  

You may also check:How to resolve the algorithm Levenshtein distance step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Convert seconds to compound duration step by step in the Frink programming language
You may also check:How to resolve the algorithm 99 bottles of beer step by step in the Nial programming language
You may also check:How to resolve the algorithm Kosaraju step by step in the Java programming language
You may also check:How to resolve the algorithm Ascending primes step by step in the Prolog programming language