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.
