반응형

 

출처: 프로그래머스 코딩 테스트 연습, https://programmers.co.kr/learn/challenges

 

 

 

** Javascript

 

 

function solution(left, right) {
    let answer = 0;
    let numbers = range(left, right, 1);
    console.log(numbers)
    for (const number of numbers) {
        let count = 0;
        for (let i = 1; i<= number; i++) {
            if (number % i === 0) count++;
        }
        if (count % 2 === 0) answer += number;
        if (count % 2 === 1) answer -= number;
    }
    return answer;
}

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

 

 

 

감탄만 나왔던 소스

 

function solution(left, right) {
    let answer = 0;
    for (let i = left; i <= right; i++) {
        if (Number.isInteger(Math.sqrt(i))) {
            answer -= i;
        } else {
            answer += i;
        }
    }
    return answer;
}

 

제곱근이 정수면 약수의 개수가 홀수니까 - i

 

 

** Python

 

def solution(left, right):
    answer = 0
    for i in range(left, right + 1):
        if (i ** 0.5).is_integer():
            answer -= i
        else:
            answer += i
    return answer

 

 

 

** Java

 

class Solution {
    public int solution(int left, int right) {
        int answer = 0;
        for (int i = left; i <= right; i++) {
            if (Math.sqrt(i) % 1 == (double) 0) {
                answer -= i;
            } else {
                answer += i;
            }
        }
        return answer;
    }
}
반응형

+ Recent posts