Discovering the Harshad number

I find myself in a predicament where the issue at hand is defined as:

Harshad/Niven numbers are positive numbers that are divisible by the sum of their digits. All single-digit numbers are Harshad numbers.

For instance, 27 is a Harshad number as 2 + 7 = 9, and 9 is a divisor of 27.

Harshad numbers can exist in consecutive clusters. The numbers 1 through 10 are Harshad numbers. Numbers 132 and 133 are both Harshad numbers. Numbers 1014, 1015, 1016, 1017 are also Harshad numbers.

Develop a function that takes a number and yields an array of two elements. The first element being the length of the Harshad cluster to which the number belongs. The second element is its position within the cluster.

Examples harshad(5) ➞ [10, 5] // cluster = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // The second element should be the layman order in the cluster, not the programming index. harshad(133) ➞ [2, 2] // cluster = [132, 133]

Therefore, I have devised a method to identify all the Harshad clusters greater than the number provided as an argument to the function, the code for which is outlined below

function track(num) {
  let a = num.toString().split("");
  let b = a.reduce((a, b) => +a + +b, 0);
  if (num % b != 0) {return;}
  console.log(num,num%b);
  if (num % b == 0) {
    num++;
    track(num);
  }

}
track(1015);

thus console.log() reveals to me 1015,1016 and 1017

cluster since they are greater than 1015 which is the input to the function. Yet, how can I determine the numbers smaller than 1015 since 1014 should also be a part of the cluster, but simply adding another IF statement does not seem logical

function track(num) {
      let a = num.toString().split("");
      let b = a.reduce((a, b) => +a + +b, 0);
      if (num % b != 0) {return;}
      console.log(num,num%b);
      if (num % b == 0) {
        num++;
        track(num);
      }
 if(num%b==0){
        num--
        track(num)
      }


    }
    track(1015);

since this approach seems to lack coherence

Answer №1

You can create two separate functions to achieve this task. One function can be used to check if a number is a harshad value, while another function can handle the collection of these numbers. The collection function can decrement and increment the value while collecting valid numbers in an array.

function harshad(value) {
    function isHarshad(value) {
        return value % Array.from(value.toString(), Number).reduce((a, b) => a + b) === 0;        
    }
    
    var cluster = [],
        left = value,
        right = value + 1;
        
    while (isHarshad(left)) cluster.unshift(left--);
    while (isHarshad(right)) cluster.push(right++);
    return [cluster.length, cluster.indexOf(value) + 1];
}

console.log(harshad(5));    // [10, 5] cluster = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(harshad(133));  // [ 2, 2] cluster = [132, 133]
console.log(harshad(1015)); // [ 4, 2] cluster = [1014, 1015, 1016, 1017]
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Give this a try:

function analyzeNumber(number) {
  const isSpecial = num => {
      let sum = num.toString().split("").reduce((a, b) => (+a) + (+b), 0);
      return num % sum === 0;
  };
  if (!isSpecial(number)) {return false;}
  let index = 1;
  let counter = 1;
  let num = number - 1;
  while(isSpecial(num)) {
    counter++;
    index++;
    num--;
  }
  num = number + 1;
  while(isSpecial(num)) {
    counter++;
    num++;
  }
  return [counter, index];
}
console.log(analyzeNumber(5));
console.log(analyzeNumber(133));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Dynamic Jinja HTML to Select Elements Dynamically

I have a unique system where forms are dynamically created based on values from a dictionary. Each form is assigned an ID corresponding to the key value and initially hidden. <div id="subforms" style="display: none" > {%for k, v in options.items() ...

Maximizing the efficiency of this JavaScript code

Is there a way to optimize this code for better efficiency? I'm trying to enhance my coding skills and would appreciate some feedback on this particular section: $(function(){ $('#buscar').focus(function(){ if(($(this).val() === ...

Check to see if the event handler is triggered and the promises are executed in sequence (syncronously)

I have a Vue button click handler that, depending on the arguments it receives, can do the following: execute request A only execute request B only execute request A and then request B sequentially (request B is only called if request A completes successf ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

Executing a JavaScript function without passing arguments does not yield the desired result

Within my JS file, I encountered an issue when trying to call one function from another. Initially, I called the function with no arguments using only its name handleResponse. However, when attempting to add arguments by changing the function signature, I ...

Is there a way to access the rear camera on a mobile device using webcam.js?

Currently, I am utilizing webcam.js from the following link: https://github.com/jhuckaby/webcamjs. When accessing the website on mobile devices, the front camera tends to open by default. My objective is to switch this default setting to access the rear ...

Storing Vue.js components as objects in a database: A step-by-step guide

Is there a way to serialize Vue.js components and store them in a database? For example, I am looking to save components like the HelloWorld component typically found in a fresh Vue installation. Any suggestions on a serialization process or package that ...

The jQuery datetimepicker fails to reflect changes made to the minDate property

I have encountered a datetimepicker object that was previously set up with the following configuration: $('#startDate').datetimepicker({ monthNames: DATE_TIME_MONTHS_NAMES, monthNamesShort: DATE_TIME_MONTHS_NAMES_SHORT, dayNames: DAT ...

What is the method for extracting JavaScript code as data from a script tag?

I have a file external (let's say bar.js) function qux() {} Then in my webpage, I include it using the script tag: <script type="text/javascript" src="bar.js"></script> I am looking for a way to retrieve the JavaScript code from within ...

Retrieving the output from a nested scope within a function

I have a scenario where I am working with a function that has a nested "then" function containing a return statement. My goal is to combine this inner return data with the outer return data. Below is the code snippet: public async getAllWidgets(): Promis ...

Issue encountered when attempting to remove an element from an array using the delete method

Whenever I attempt to remove an input that has been added, an error message saying "Value is NULL" pops up. I'm looking for a solution where only the selected inputs are deleted when I click on DELETE, instead of all inputs being removed. The myFuncti ...

Tips for sending props to Material UI components

Hey there! I'm currently working on a progressbar component that utilizes animations to animate the progress. I've styled the component using Material UI classes and integrated it into another component where I pass props to customize the progres ...

Form validation has not passed the necessary checks

Struggling to create a new user POST form with Bootstrap form validation but encountering an issue. The button code is as follows: <button class="btn btn-primary btn-addUser" type="submit">Add User</button> This button trig ...

Word with the Most Points

I have created a code to determine the highest scoring word as a string, however when I calculate all words and attempt to display the results, I am encountering an issue where all results are showing as: NaN function high(x) { var words = x.split(&ap ...

What is the reason behind having to restart the npm server each time?

When first learning Reactjs with VSCode, there was no need to restart the server after making modifications. However, now I find that I must restart the server every time I make a change in order for those changes to be applied. ...

How can I retrieve both the keys and values of $scope in AngularJS?

Here is the code I have written to retrieve all key values using $scope. $scope.Signup={}; $scope.Message=''; $scope.SubmitPhysicianSignup = function() { var url = site_url + 'webservices/physician_signup'; //console.lo ...

Why is the updated index.html not loading with the root request?

I'm currently working on an Angular app and facing an issue with the index.html file not being updated when changes are made. I have noticed that even after modifying the index.html file, requests to localhost:8000 do not reflect the updates. This pro ...

Is assigning key value pairs a statement in JavaScript?

I am curious to learn about the following code snippet: var a = {x:function(){},y:function(){}} Can we consider x:function(){} to be a statement within this code? ...

Adding caller information to error stack trace in a Node.js application

I have a function named inner that executes a series of asynchronous operations: function inner(input) { return step1(input) .then(step2) .then(step3) .catch((e) => { throw e }) } I propagate the error from inner so I can m ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...