Find the largest composite number that divides N but is strictly lesser than N

Given a composite number N, the task is to find the largest composite number that divides N and is strictly lesser than N. If there is no such number exist print -1.

Examples:

Input: N = 16
Output: 8
Explanation:
All numbers that divide 16 are { 1, 2, 4, 8, 16 }
out of which 8 is largest composite number(lesser than 16) that divides 16.



Input: N = 100
Output: -1

Approach:
Since N is a composite number, therefore N can be the product of two numbers such that one is prime number and another is a composite number and if we can’t find such a pair for N then the largest composite number which is less than N that divides N doesn’t exist.
To find the largest composite number find the smallest prime number(say a) that divides N. Then the largest composite number that divides N and less than N can be given by (N/a).

Following are the steps:

  1. Find the smallest prime number of N (say a).
  2. Check if (N/a) is prime or not. If yes then we can’t find the largest composite number.
  3. Else (N/a) is the largest composite number that divides N and less than N.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the largest
// composite number that divides
// N which is less than N
#include <bits/stdc++.h>
using namespace std;
  
// Function to check whether
// a number is prime or not
bool isPrime(int n)
{
    // Corner case
    if (n <= 1)
        return false;
  
    // Check from 2 to n-1
    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;
  
    return true;
}
  
// Function that find the largest
// composite number which divides
// N and less than N
int getSmallestPrimefactor(int n)
{
    // Find the prime number
    for (int i = 2; i <= sqrt(n); i++) {
        if (n % i == 0)
            return i;
    }
}
  
// Driver's Code
int main()
{
    int N = 100;
    int a;
  
    // Get the smallest prime
    // factor
    a = getSmallestPrimefactor(N);
  
    // Check if (N/a) is prime
    // or not
    // If Yes print "-1"
    if (isPrime(N / a)) {
        cout << "-1";
    }
  
    // Else print largest composite
    // number (N/a)
    else {
        cout << N / a;
    }
    return 0;
}

chevron_right


Output:

50

Time Complexity: O(sqrt(N))




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.