Calculate Pow(x,n) using recursion

 

 

 

So, there are n Xs and to calculate X to the power n, we simply keep on multiplying with X all the time, exactly n-1 multiplications.

 

And if we want to write a program to calculate x to the power n, the simplest thing that comes to our mind is that we can start with a variable.

Let’s say we want to start with a variable result(res), initialize it to 1 and then we can simply run a loop from 1 to n and keep multiplying result(res) with x.

 

So, result becomes result*x.

In this case, you are performing n multiplications because you are initiating the variable to 1 instead of x, but it also takes care of the condition when n is equal to 0 and as we know x to the power 0 or any number to the power 0 is 1.

 

And as we can see for an input n, we are running just one loop n times, so it should be pretty evident that the time taken here in this case would be proportional to n or we can also say that the time complexity of this algorithm would be O(n).

 

 

 

 

Now, Albert and Pinto are given an assignment to calculate x to the power n using recursion.

Albert and Pinto come up with two different solutions.

To solve a problem using recursion, we first need to define a recurrence relation or a recursive definition.

 

Albert says that x to the power n can be written as x*x^(n-1) and this is true for all n greater than 0.

For n=0, x to the power 0 is simply equal to 1.

So, Albert writes a function Pow that takes two arguments x and n, and if n is 0 then simply return 1, else return x*Pow(n-1).

This is Albert’s implementation, and it will work fine for all n>=0.

 

If we try to calculate x^8 with this algorithm, we make a recursive call, first to calculate x^7, and then x^7 goes on to make a recursive call to calculate x^6, and we keep on making recursive calls till x^0, which simply returns 1.

 

Now, let’s see what Pinto’s solution is.

Pinto says that x^n can be written as x^(n/2) * x^(n/2) if n is an even number, and x^n is equal to x * x^(n-1) if n is odd. And x^n is equal to 1 if n=0.

 

So, Pinto also writes a function Pow that takes two arguments x and n.

And it also goes like, if n=0 it return 1, else if n%2==0 then store Pow(x, n/2) in a variable y making recursive call, and return y*y.

Finally, if n is odd then we simply return x * x^(n-1).

This is Pinto’s implementation, and it also works fine for all n>=0.

 

When we calculate x^8 with this algorithm, then we make a call to x^4, and further x^4 recursively makes a call to calculate x^2 and then x^1, and x^0.

 

While Albert’s program goes nine steps in this recursion tree, Pinto’s program only goes 5 steps.

If we analyze the recurrence relation of these two algorithms, then Albert’s algorithm’s time taken by is proportional to n, or simply say O(n) in terms of time complexity.

Pinto’s program is O(log n) in terms of time complexity.

 

 

 

 

↓ 참고 사이트

https://www.youtube.com/watch?v=wAyrtLAeWvI&list=PL2_aWCzGMAwLz3g66WrxFGSXvSsvyfzCO&index=7 

 

 

 

문제 

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

 

 

입출력

Example 1:

Input: nums = [0,1,0,3,12]

Output: [1,3,12,0,0]

 

Example 2:

Input: nums = [0]

Output: [0]

 

 

제약

Constraints:

  • 1 <= nums.length <= 10^4
  • -2^31 <= nums[i] <= 2^31 - 1

 

 

코드

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    let isZero = false;
    for(let i=0; i<nums.length; i++) {
        if(nums[i] === 0) {
            isZero = true;
            for(let j=i; j<nums.length, isZero; j++) {
                if(nums[j] != 0) {
                    isZero = false;
                    let temp = nums.splice(i, j-i);
                    nums.push(...temp);
                }
            }
        }
    }
};

 

 

 

문제 

온라인 저지에 가입한 사람들의 나이와 이름이 가입한 순서대로 주어진다. 이때, 회원들을 나이가 증가하는 순으로, 나이가 같으면 먼저 가입한 사람이 앞에 오는 순서로 정렬하는 프로그램을 작성하시오.

 

입력

첫째 줄에 온라인 저지 회원의 수 N이 주어진다. (1 ≤ N ≤ 100,000)

둘째 줄부터 N개의 줄에는 각 회원의 나이와 이름이 공백으로 구분되어 주어진다. 나이는 1보다 크거나 같으며, 200보다 작거나 같은 정수이고, 이름은 알파벳 대소문자로 이루어져 있고, 길이가 100보다 작거나 같은 문자열이다. 입력은 가입한 순서로 주어진다.

 

출력 

첫째 줄부터 총 N개의 줄에 걸쳐 온라인 저지 회원을 나이 순, 나이가 같으면 가입한 순으로 한 줄에 한 명씩 나이와 이름을 공백으로 구분해 출력한다.

 

예제1 

입력:

3

21 Junkyu

21 Dohyun

20 Sunyoung

출력

20 Sunyoung

21 Junkyu

21 Dohyun

 

 

코드

let input = require('fs').readFileSync('/dev/stdin').toString().split('\n');
let total = input.shift();
let user = [];

for(let i=0; i<total; i++) {
    user[i] = input[i].split(' ');
}

user.sort((a,b) => a[0] - b[0]);

for(let i=0; i<total; i++) {
    console.log(user[i][0]+' '+user[i][1]);
}

 

 

+ Recent posts