자료구조 & 알고리즘/알고리즘

[JAVA] 정수의 합을 구하는 알고리즘

ReBugs 2023. 1. 18.

Do it! 자료구조와 함께 배우는 알고리즘 입문[자바편] 연습문제와 실습문제입니다.


1부터 n까지 정수 합

while문

import java.util.Scanner;
public class Test{
	static int SumWile(int n)
	{
		int i = 1;
		int sum = 0;
		while(i <= n)
		{
			sum+=i;
			++i;
		}
		return sum;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("정수를 입력하세요 : ");
		int n = sc.nextInt();
		System.out.println("1부터 "+ n +"까지 합계 : " + SumWile(n));
	}
}
/*
정수를 입력하세요 : 100
1부터 100까지 합계 : 5050
*/

 

i 값이 n+1이 됨을 확인하기

위 코드에서 while문이 종료될 때 변수 i 값이 n+1이 됨을 확인하기(변수 i 값을 출력하도록)

import java.util.Scanner;
public class Test{
	static int SumWile(int n)
	{
		int i = 1;
		int sum = 0;
		while(i <= n)
		{
			sum+=i;
			++i;
		}
		System.out.println(i);
		return sum;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("정수를 입력하세요 : ");
		int n = sc.nextInt();
		System.out.println("1부터 "+ n +"까지 합계 : " + SumWile(n));
	}
}
/*
정수를 입력하세요 : 100
101
1부터 100까지 합계 : 5050
*/
설명
i는 n까지 증가가 된 후에도 ++i가 되었기 때문에 i는 n+1이 된다.

 

 

for문

import java.util.Scanner;
public class Test{
	static int SumFor(int n)
	{
		int sum = 0;
		for(int i = 1; i <= n; ++i)sum += i;
		return sum;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("정수를 입력하세요 : ");
		int n = sc.nextInt();
		System.out.println("1부터 "+ n +"까지 합계 : " + SumFor(n));
	}
}
/*
정수를 입력하세요 : 100
1부터 100까지 합계 : 5050
*/

 

응용하여 출력

n이 7이면 '1 + 2 + 3 + 4 + 5 + 6 + 7 = 28' 로 출력하는 프로그램을 작성하시오

import java.util.Scanner;
public class Test{
	static void SumFor(int n)
	{
		int sum = 0;
		for(int i = 1; i <= n; ++i) sum += i;
		for(int i = 1; i <= n; ++i)
		{
			if(i == n)
			{
				 System.out.print(i + " = ");
				 break;
			}
			System.out.print(i+" + ");
		}
		System.out.println(sum);
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("정수를 입력하세요 : ");
		int n = sc.nextInt();
		SumFor(n);
	}
}
/*
정수를 입력하세요 : 7
1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
*/
설명
먼저 정수들의 합을 저장하고, 1부터 n까지의 수를 차례대로 출력하되, 중간에 " + " 문자열을 추가시킨다.
for루프의 변수 i가 n과 같으면 i와 문자열 " = "를 출력시킨다.
그 후 처음에 구한 정수들의 합을 출력한다.

 

 

가우스 덧셈

1부터 10까지의 합은 (1+10) * 5 와 같은 방법으로 구할 수 있다. 가우스 덧셈이라는 방법을 이용하여 1부터 n까지의 정수 합을 구하는 프로그램 작성

가우스 덧셈
1부터 10까지 더한다고 할 때
첫 항과 마지막 항을 더한(1+10) 뒤 전체 항의 개수(10)를 2로 나눈 값(5)을 곱한다.
(1+10) * (10 / 2)
이를 수식으로 나타내면 n * (n+1)  / 2 이다.
import java.util.Scanner;
public class Test{
	static int SumGauss(int n)
	{
		return (n*(n+1))/2;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("정수를 입력하세요 : ");
		int n = sc.nextInt();
		System.out.println(SumGauss(n));
	}
}
/*
정수를 입력하세요 : 100
5050
*/

 

두 수 사이의 정수 합 구하기

정수 a, b를 포함하여 그 사이의 모든 정수의 합을 구하여 리턴하는 메서드를 작성

(a와 b의 대소 관계에 상관없이 합을 구하기(a=3, b=5이면 12를 리턴 / a=6, b=4이면 15를 리턴)

import java.util.Scanner;
public class Test{
	static int Sumof(int a, int b)
	{
		int sum = 0;
		if(b<a)
		{ //swap
			int tmp = a;
			a = b;
			b = tmp;
		}
		for(int i = a; i <= b; ++i) sum += i;
		return sum;
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int []arr = new int[2];
		System.out.print("정수를 두 개를 입력하세요 : ");
		for(int i = 0; i < 2; ++i)arr[i] = sc.nextInt();
		System.out.println(Sumof(arr[0], arr[1]));
	}
}
/*
정수를 두 개를 입력하세요 : 50 100
3825
*/
설명
매개 변수 a와 b중에 a가 더 크면 a와 b의 값을 바꾼다.(swap)
그 후 a부터 b까지의 수를 모두 더한 값을 리턴한다.

댓글