Print all the perfect squares in a range

By | October 30, 2023

Print all the perfect squares in a range i.e. a and b are the lower and upper bounds respectively. So print all the perfect squares between them and both are inclusive.

Examples:

Input: a = 1, b = 10 
Output: 1, 4, 9

Input: a = 10, b = 100 
Output: 16, 25, 36, 49, 64, 81, 100

RECOMMENDED: Find the Minimum element in a Sorted and Rotated Array

#include <iostream>
using namespace std;

void print(int a, int b) {
    int i, c = 0;
    for (i = 1; i <= b; i = i + c + 1) {
        if (i >= a)
            cout << i << " ";
        c = c + 2;
    }
}

int main() {
    int lower_bound = 10, upper_bound = 99;
    print(lower_bound, upper_bound);
    return 0;
}

Output:

16, 25, 36, 49, 64, 81

Time Complexity:

Print function: O(b) due to loop
Main function: O(b) due to the print function
Overall: O(b)

Space Complexity:

Constants (a, b, i, c) and standard I/O result in O(1) space

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.