How to resolve the algorithm Harshad or Niven series step by step in the F# programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Harshad or Niven series step by step in the F# programming language

Table of Contents

Problem Statement

The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits. For example,   42   is a Harshad number as   42   is divisible by   (4 + 2)   without remainder. Assume that the series is defined as the numbers in increasing order.

The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to:

Show your output here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Harshad or Niven series step by step in the F# programming language

Source code in the fsharp programming language

let divides d n = 
    match bigint.DivRem(n, d) with
    | (_, rest) -> rest = 0I

let splitToInt (str:string) = List.init str.Length (fun i -> ((int str.[i]) - (int "0".[0])))

let harshads =
    let rec loop n = seq {
        let sum = List.fold (+) 0 (splitToInt (n.ToString()))
        if divides (bigint sum) n then yield n
        yield! loop (n + 1I)
    }
    loop 1I

[<EntryPoint>]
let main argv = 
    for h in (Seq.take 20 harshads) do printf "%A " h
    printfn ""
    printfn "%A" (Seq.find (fun n -> n > 1000I) harshads)
    0


  

You may also check:How to resolve the algorithm Self-describing numbers step by step in the Wren programming language
You may also check:How to resolve the algorithm Left factorials step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Multiplication tables step by step in the Phixmonti programming language
You may also check:How to resolve the algorithm Old Russian measure of length step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Additive primes step by step in the uBasic/4tH programming language