Language_Coder 549 : 반복제어문3 - 자가진단1

boom.jun.cho·2022년 4월 17일
0

Language_Coder_JUNGOL

목록 보기
99/197

문제

자연수 n을 입력받고 1부터 홀수를 차례대로 더해나가면서 합이 n 이상이면 그 때까지 더해진 홀수의 개수와 그 합을 출력하는 프로그램을 작성하시오.

입력

100

출력

10 100

코드

package com.jungol.algorihm099;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int sum = 0;
        int cnt = 0;

        for(int i = 1; i <= n; i++) {
            if(i % 2 != 0) {
                sum += i;
                cnt++;

                if (sum >= n) {
                    break;
                }
            }
        }
            System.out.print(cnt + " ");
            System.out.println(sum);
    }
    sc.close;
}
profile
하루하루 최선을

0개의 댓글