완전제곱수 1977번

박진석·2025년 1월 14일
0

문제
M과 N이 주어질 때 M이상 N이하의 자연수 중 완전제곱수인 것을 모두 골라 그 합을 구하고 그 중 최솟값을 찾는 프로그램을 작성하시오. 예를 들어 M=60, N=100인 경우 60이상 100이하의 자연수 중 완전제곱수는 64, 81, 100 이렇게 총 3개가 있으므로 그 합은 245가 되고 이 중 최솟값은 64가 된다.

입력
첫째 줄에 M이, 둘째 줄에 N이 주어진다. M과 N은 10000이하의 자연수이며 M은 N보다 같거나 작다.

출력
M이상 N이하의 자연수 중 완전제곱수인 것을 모두 찾아 첫째 줄에 그 합을, 둘째 줄에 그 중 최솟값을 출력한다. 단, M이상 N이하의 자연수 중 완전제곱수가 없을 경우는 첫째 줄에 -1을 출력한다.

Solution 1.

(Inefficient)

We are checking all numbers for being perfect squares within in the range.
This method is checking divisors inefficiently. The time complexity is O(n²).

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

int main() {

    int m, n;
    vector<int> result;

    cin >> m >> n;

    for(int i = m; i <= n; i++) {        
        for(int j = 1; j <= i; j++){
            if(i % j == 0){
                if(i / j == j){
                    result.push_back(i);
                    break;
                }
            }
        }
    }

    int sum = 0;
    for(int i = 0; i < result.size(); i++){
        sum += result[i];
    }

    if(sum == 0){
        cout << -1;
    }
    else {
        cout << sum << '\n';
        cout << result[0];
    }
}

Solution 2.

(Efficient)

Instead of checking all numbers for being perfect squares, we work directly with square roots.
This method is more efficient as the time complexity is O(√n).
Also, it has simpler logic that directly generates perfect squares instead of checking divisors.

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

int main() {
    int m, n;
    vector<int> result;
    
    cin >> m >> n;
    
    // Find the first perfect square >= m
    int start = ceil(sqrt(m));
    // Find the last perfect square <= n
    int end = floor(sqrt(n));
    
    // Check all perfect squares in range
    for(int i = start; i <= end; i++) {
        result.push_back(i * i);
    }
    
    int sum = 0;
    for(int num : result) {
        sum += num;
    }
    
    if(result.empty()) {
        cout << -1;
    } else {
        cout << sum << '\n';
        cout << result[0];
    }
}

0개의 댓글