https://www.acmicpc.net/problem/1977

 

1977번: 완전제곱수

M과 N이 주어질 때 M이상 N이하의 자연수 중 완전제곱수인 것을 모두 골라 그 합을 구하고 그 중 최솟값을 찾는 프로그램을 작성하시오. 예를 들어 M=60, N=100인 경우 60이상 100이하의 자연수 중 완

www.acmicpc.net

풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Main {

	public static void main(String[] args) throws NumberFormatException, IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int m = Integer.parseInt(br.readLine());
		int n = Integer.parseInt(br.readLine());
		
		ArrayList<Integer> square = new ArrayList<Integer>();
		
		for(int i = 1; i <= 100; i++) {
			int s = i * i;
			
			if((s >= m) && (s <= n)) {
				square.add(s);
			}
		}
		
		int sum = 0;
		
		for(int i = 0; i < square.size(); i++) {
			sum += square.get(i);
		}
		
		if(sum == 0) {
			System.out.println("-1");
		} else {
			System.out.println(sum + "\n" + square.get(0));
		}
	}
}

+ Recent posts