본문 바로가기
코딩테스트/프로그래머스

[프로그래머스/Java] LV.1 나머지가 1이 되는 수 찾기

by ⓞㅖ롱 2022. 9. 13.

연휴동안 잘 놀고 다시 코테공부 시작을 위해 쉬운 문제부터 풀기 시작..

처음부터 어려운 문제 풀면 멘탈바사삭 될 수 있음 ^^~

 

내 코드

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int n) {
    int answer = 0;
    int x = 2;

    while(1){
       if(n % x == 1){
            answer = x;
            break;
        }
        x++;
    }

    return answer;
}

다른사람 풀이

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

int solution(int n) {
    int answer = 0;

    for(int i=1; i<n; i++)
    {
        if(n % i == 1)
        {
            answer = i;
            break;
        }
    }

    return answer;
}

쉬운 문제라 여러가지 많았는데 이게 가장 나은 것 같다

나는 while문으로 해결해서 증감연산자를 else에 넣어줬는데 for문을 쓰면 if로만 해결가능