How to resolve the algorithm Harshad or Niven series step by step in the Julia programming language
How to resolve the algorithm Harshad or Niven series step by step in the Julia 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 Julia programming language
The provided Julia code defines several functions for working with Harshad numbers, which are numbers that are divisible by the sum of their digits.
isharshad(x): This function checks if a given number x
is a Harshad number by calculating the sum of its digits and checking if x
is divisible by that sum. It returns true
if x
is a Harshad number and false
otherwise.
nextharshad(x): This function finds the next Harshad number after x
. It does this by incrementing x
by 1 until it finds a number that is a Harshad number.
harshads(n): This function returns a vector of the first n
Harshad numbers. It initializes a vector h
with n
elements and sets the first element to 1. Then, for each subsequent element, it uses nextharshad
to find the next Harshad number after the previous element and stores it in the vector. Finally, it returns the vector h
.
Usage:
The code demonstrates the usage of these functions by printing the first 20 Harshad numbers and finding the first Harshad number after 1001.
Output:
First 20 harshad numbers: 1, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 21, 22, 24, 26, 27, 28, 30, 32, 36
First harshad number after 1001: 1008
Source code in the julia programming language
isharshad(x) = x % sum(digits(x)) == 0
nextharshad(x) = begin while !isharshad(x+1) x += 1 end; return x + 1 end
function harshads(n::Integer)
h = Vector{typeof(n)}(n)
h[1] = 1
for j in 2:n
h[j] = nextharshad(h[j-1])
end
return h
end
println("First 20 harshad numbers: ", join(harshads(20), ", "))
println("First harshad number after 1001: ", nextharshad(1000))
You may also check:How to resolve the algorithm Idiomatically determine all the characters that can be used for symbols step by step in the Java programming language
You may also check:How to resolve the algorithm Price fraction step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Sorting algorithms/Shell sort step by step in the Wren programming language
You may also check:How to resolve the algorithm DNS query step by step in the V (Vlang) programming language
You may also check:How to resolve the algorithm Day of the week step by step in the Scala programming language