티스토리 뷰

문제
n이 주어졌을 때, 1부터 n까지 합을 구하는 프로그램을 작성하시오.
입력
첫째 줄에 n (1 ≤ n ≤ 10,000)이 주어진다.
출력
1부터 n까지 합을 출력한다.
풀이 과정
1부터 n까지의 합을 저장하여 출력하면 되는 반복문 기초 문제이다.
그러나, 1부터 n까지의 합에 대한 수학 공식을 알고 있다면 이 또한 사용이 가능하다.
C - 반복문
#include <stdio.h>
int main(void) {
int n; scanf("%d", &n);
int result = 0;
for (int i = 1; i <= n; i++)
result += i;
printf("%d", result);
return 0;
}
C - 수학
#include <stdio.h>
int main(void) {
int n; scanf("%d", &n);
printf("%d", n*(n+1)/2);
return 0;
}
C++ - 반복문
#include <iostream>
using namespace std;
int main(void) {
int n; cin >> n;
int result = 0;
for (int i = 1; i <= n; i++)
result += i;
cout << result;
return 0;
}
C++ - 수학
#include <iostream>
using namespace std;
int main(void) {
int n; cin >> n;
cout << n*(n+1)/2;
return 0;
}
Python - 반복문
import sys
input = sys.stdin.readline
n = int(input().rstrip())
result = 0
for i in range(1, n+1):
result += i
print(result)
Python - 수학
import sys
input = sys.stdin.readline
n = int(input().rstrip())
print(n*(n+1)//2)
Java - 반복문
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int result = 0;
for (int i = 1; i <= n; i++)
result += i;
System.out.println(result);
}
}
Java - 수학
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n*(n+1)/2);
}
}'(예전 글) > PS' 카테고리의 다른 글
| [ BOJ ] 25314 : 코딩은 체육과목 입니다 ( BRONZE 5 ) / C, C++, Python, Java (2) | 2023.09.05 |
|---|---|
| [ BOJ ] 25304 : 영수증 ( BRONZE 4 ) / C, C++, Python, Java (0) | 2023.09.05 |
| [ BOJ ] 10950 : A+B - 3 ( BRONZE 5 ) / C, C++, Python, Java (0) | 2023.09.03 |
| [ BOJ ] 2739 : 구구단 ( BRONZE 5 ) / C, C++, Python, Java (0) | 2023.09.02 |
| [ BOJ ] 2480 : 주사위 세개 ( BRONZE 4 ) / C, C++, Python, Java (0) | 2023.09.02 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- segment-tree
- string
- codeup
- bruteforcing
- bitmask
- Prefix-Sum
- java
- math
- 백준
- C++
- sparse_table
- kmp
- Greedy
- DP
- backtracking
- knapsack
- ad_hoc
- number_theory
- queue
- Python
- Sort
- lazy-propagation
- C
- BOJ
- PS
- lca
- BFS
- stack
- Binary-Search
- implementation
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
글 보관함
