Largest integer upto N having greatest prime factor greater than its square root
Given a positive integer N, the task is to find the largest number in the range [1, N] such that the square root of the number is less than its greatest prime factor.
Input: N = 15
Output: 15
Explanation: The prime factors of 15 are {3, 5}. The square root of 15 is 3.87 (i.e, 3.87 < 5). Therefore 15 is the largest valid integer in the given range.Input: N = 25
Output: 23
Approach: The given problem can be solved by using the Sieve of Eratosthenes with a few modifications. Create an array gpf[], which stores the Greatest Prime Factor of all integers in the given range. Initially, gpf[] = {0}. Using Sieve, initialize all the indices of the array gpf[] with the greatest prime factor of the respective index similar to the algorithm discussed in this article.
Now, iterate over the range [N, 1] in a reverse manner and print the first integer whose square root of the number is less than its greatest prime factor.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; const int maxn = 100001; // Stores the Greatest Prime Factorint gpf[maxn]; // Modified Sieve to find the Greatest// Prime Factor of all integers in the// range [1, maxn]void modifiedSieve(){ // Initialize the array with 0 memset(gpf, 0, sizeof(gpf)); gpf[0] = 0; gpf[1] = 1; // Iterate through all values of i for (int i = 2; i < maxn; i++) { // If i is not a prime number if (gpf[i] > 0) continue; // Update the multiples of i for (int j = i; j < maxn; j += i) { gpf[j] = max(i, gpf[j]); } }} // Function to find integer in the range// [1, N] such that its Greatest Prime// factor is greater than its square rootint greatestValidInt(int N){ modifiedSieve(); // Iterate through all values of // i in the range [N, 1] for (int i = N; i > 0; i--) { // If greatest prime factor of i // is greater than its sqare root if (gpf[i] > sqrt(i)) { // Return answer return i; } } // If no valid integer exist return -1;} // Driver Codeint main(){ int N = 25; cout << greatestValidInt(N); return 0;} |
23
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.


