ODD012 Editorial

PROBLEM LINK:

Contest problem

Author: Maaz Bin Asad
Tester: Maaz Bin Asad
Editorialist: Pratima Singh

DIFFICULTY:

CAKEWALK, EASY

PREREQUISITES:

Simple observation, no prerequisites.

PROBLEM:

You are given a positive integer N. Find smallest integer M, such that M>=N and M can be represented as sum of consecutive odd numbers starting from 1.

EXPLANATION:

We need to find a number M, greater than the given number N, such that it can be represented as the sum of consecutive odd numbers starting from 1.
We have to initialize an iterator from 1 and keep on jumping to the following odd number i.e. increment the iterator by 2 after each iteration and add it to a variable s i.e. Store the sum of all odd numbers starting from 1. Then break the loop and print the sum(s) after the value of the sum becomes greater than or equal to N.

SOLUTION:

Editorialist's Solution
#include<bits/stdc++.h>
#include<iostream>
using namespace std;

int main(){
    int t;
    cin>>t;
    while(t--){
        int n, m, s;
        s = 0;
        cin>>n;
        int max_n = INT_MAX;
        for(int i=1;i<=max_n;i+=2){
            s+=i;
            if(s>=n){
                cout<<s<<endl;
                break;
            }
        }
    }
    return 0;
}

You can also use the fact that sum of odd numbers results in a perfect square.
1 = 1
1 + 3 = 4
1 + 3 + 5 = 9
1 + 3 + 5 + 7 = 16
So all you need to find a number more than or equal to this number which is a perfect square

from math import sqrt
for _ in range(int(input())):
    '''
    #option 1
    N = int(input())    
    Ns = int(sqrt(N))       
    if Ns * Ns == N:
        print(N)
    else:
        print((Ns + 1) ** 2)
    '''
    #option 2
    N = int(input())    
    i = 1
    while True:
        if i * i >= N:
            print(i * i)
            break
        i += 1
        
    ```

Thanks a lot for sharing your solution. Great approach indeed! :+1: