Skip to content
자연수 10진수기술 정리

Converting natural numbers (decimal) to octal and hexadecimal & the Fibonacci array

1 min readTech notesMoved from my Tistory blogRead the Korean original

To convert a natural number (decimal) to octal or hexadecimal, pass the base you want as the argument to the toString() function.

js
const NUM = 250;

NUM.toString(2~36)

If toString() is given a radix that isn't between 2 and 36, a RangeError is thrown.

For details, see https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/toString

Number.prototype.toString() - JavaScript | MDN

Next, I learned about the Fibonacci array. A Fibonacci array is an array where each number is the sum of the two numbers right before it.

An example of a Fibonacci array

js
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

I used a loop to get the value at the n-th position given as the parameter. Below is how I solved it.

js
function fib(n){ //create function fib and take n as the parameter / assume n is 5

    First, create result, a fixed array object
    const result = [0,1];

	for(let i=2; i<=n; i++){
    	const a = result[i-2]; // store the value two indexes before result[i] in a variable named a
        const b = result[i-1]; // store the value one index before result[i] in a variable named b
        
        result.push(a+b); // insert the sum of a+b at the end of the result array result = [0,1,1,2,3,5]
        
    }
    
    return result[n-1]  // return the 5th value in the result array (-1 because array indexes start at 0)
}
  • #Decimal Conversion
  • #Loops
  • #Fibonacci Sequence

More in Tech notes