알고리즘

[백준 8393] n이 주어졌을 때, 1부터 n까지 합 반복문없이

silver-w 2024. 12. 9. 21:46

합의 공식 n×(n+1)​ / 2 이용

 

※ 반복문 있이 풀었을 때

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = 0;
        for (int i = 1; i < a+1; i++) {
            b += i;
        }
        System.out.println(b);
    }
}

 

※ 반복문 없이 풀었을 때

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int result = a * (a+1) /2;
        System.out.println(result);
    }
}