Programmers Q4. ์ฝ์์ ํฉ
๐ What I learned after solving the algorithm questions.
๋ฌธ์ ๋งํฌ(Question link)
Approach:
์ฝ์(divisor)๋ ์ซ์๋ฅผ ๋๋์์ ๋ ๋๋์ด ๋จ์ด์ง๊ฒ ํ๋ ์์ด๋ฏ๋ก ๋๋จธ์ง๊ฐ 0์ธ ์๋ฅผ ๋ชจ๋ ๊ตฌํด์ ๋ํ๋ฉด ๋๋ค.
Solution:
modulus ์ฌ์ฉํด์ n์ ๋๋จธ์ง ๊ฐ์ ๊ตฌํ๋ค. ๋ง์ฝ ๋๋จธ์ง๊ฐ 0์ด๋ฉด answer์ ๋ํด์ค๋ค. ์ด ๋, ๋๋๋ ์ x๋ n๋ณด๋ค ์๊ฑฐ๋ ๊ฐ๋ค.
Code 1: using if statement
public class Solution4 {
public int solution(int n) {
int answer = 0;
int x;
for(x=1;x<=n;x++){
if(n % x == 0){
answer+=x;
}
}
return answer;
}
public static void main(String[] args) {
Solution4 solution4 = new Solution4();
int answer = solution4.solution(12);
System.out.println("answer = " + answer);
}
}
What I learned:
๋งค์ฐ ๊ฐ๋จํ๊ฒ ํ์ด์ ์ข์ํ๋๋ฐ ๋ค๋ฅธ ์ฌ๋์ ํ์ด๋ฅผ ๋ณด๊ณ ๋๋๋ค.
์ฃผ์ด์ง ์๋ฅผ 2๋ก ๋๋๋ฉด ๊ทธ๋ฅผ ์ด๊ณผํ๋ ์์์๋ ์๊ธฐ ์์ ๋ง๊ณ ๋ ๋์ด์ ์ฝ์๊ฐ ์๋ค. ๊ทธ๋ฌ๋ฏ๋ก for loop์ ๋๋ฆด ๋ n๋งํผ ๋๋ฆฌ์ง ๋ง๊ณ n/2๋งํผ๋ง ๋๋ ค์ฃผ๋ฉด ์ฃผ์ด์ง ์๋ฅผ ์ ์ธํ ๋ชจ๋ ์ฝ์๋ฅผ ๊ตฌํ ์ ์๋ค. ์ด ๋ชจ๋ ์ฝ์๋ค์ ๋ํด์ฃผ๊ณ ๋ง์ง๋ง์ ์ฃผ์ด์ง ์๋ฅผ ๋ํด์ฃผ๋ฉด ํฉ์ ๊ตฌํ ์ ์๋ค. ๋ฐ๋ณต๋ฌธ์ ๋ฐ์ผ๋ก ์ค์ผ ์ ์๋ ๋ฐฉ๋ฒ์ด๋ค.
Code refactored: less looping
public class Solution4 {
public int solution(int n) {
int answer = 0;
int x;
for(x=1;x<=n/2;x++){
if(n % x == 0){
answer+=x;
}
}
return answer+n;
}
public static void main(String[] args) {
Solution4 solution4 = new Solution4();
int answer = solution4.solution(12);
System.out.println("answer = " + answer);
}
}
Leave a comment