Problem Description: Create a function that takes a number and finds the factors of it, listing them in descending order in an array.
If the parameter is not an integer or less than 1, return -1. In C# return an empty array.
For Example: factors(54) should return [54, 27, 18, 9, 6, 3, 2, 1]
Level:7kyu
Link to kata: Finding Factors
A very basic problem in form of a Kata which can be used to understand how different operators work in Javscript. We are given a number and we have to write a function which can find the factors of that number and list them in decreasing order. We have to also verify that whether the given number is an integer or not.
We first of all parse the given number with base 10 and check if the given number and its parsed version are equal. We also check if its greater than or equal to 1. If the above condition is satisfied then we pass the given input integer to a function called "factor".
In the function factor we initialize an array "ans". If the given integer is equal to 1 then we just return 1 and that is the end of our function. In other cases we run through a while loop from 1 to a value equal to half that of the input. If our input is divisible by the looping index then we push it to the "ans" array. At last we push the input to "ans" array because every number is a factor of itself.
Once we are done looping through the while loop we output the value of "ans" in reverse order by using Array.reverse() function.
Here is a link to the code: Kata Day 22
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment