Kth largest factor of number N
Last Updated :
23 Jul, 2025
Given two positive integers N and K, the task is to print the Kth largest factor of N.
Input: N = 12, K = 3
Output: 4
Explanation: The factors of 12 are {1, 2, 3, 4, 6, 12}. The largest factor is 12 and the 3rd largest factor is 4.
Input: N = 30, K = 2
Output: 15
Explanation: The factors of 30 are {1, 2, 3, 5, 6, 10, 15, 30} and the 2nd largest factor is 15.
Approach: The idea is to check for each number in the range [N, 1], and print the Kth number that divides N completely.
Iterate through the loop from N to 0. Now, for each number in this loop:
- Check if it divides N or not.
- If N is divisible by the current number, decrement the value of K by 1.
- When K becomes 0, this means that the current number is the Kth largest factor of N.
- Print the answer according to the above observation.
Below is the implementation of the above approach:
C
// C program for the above approach
#include <stdio.h>
// Function to print Kth largest
// factor of N
int KthLargestFactor(int N, int K)
{
// Check for numbers
// in the range [N, 1]
for (int i = N; i > 0; i--) {
// Check if i is a factor of N
if (N % i == 0)
// If Yes, reduce K by 1
K--;
// If K is 0, it means
// i is the required
// Kth factor of N
if (K == 0) {
return i;
}
}
// When K is more
// than the factors of N
return -1;
}
// Driver Code
int main()
{
int N = 12, K = 3;
printf("%d", KthLargestFactor(N, K));
return 0;
}
C++
// C++ program for the above approach
#include <iostream>
using namespace std;
// Function to print Kth largest
// factor of N
int KthLargestFactor(int N, int K)
{
// Check for numbers
// in the range [N, 1]
for (int i = N; i > 0; i--) {
// Check if i is a factor of N
if (N % i == 0)
// If Yes, reduce K by 1
K--;
// If K is 0, it means
// i is the required
// Kth factor of N
if (K == 0) {
return i;
}
}
// When K is more
// than the factors of N
return -1;
}
// Driver Code
int main()
{
int N = 12, K = 3;
cout << KthLargestFactor(N, K);
}
Java
// Java program for the above approach
import java.io.*;
class GFG {
// Function to print Kth largest
// factor of N
static int KthLargestFactor(int N, int K)
{
// Check for numbers
// in the range [N, 1]
for (int i = N; i > 0; i--) {
// Check if i is a factor of N
if (N % i == 0)
// If Yes, reduce K by 1
K--;
// If K is 0, it means
// i is the required
// Kth factor of N
if (K == 0) {
return i;
}
}
// When K is more
// than the factors of N
return -1;
}
// Driver Code
public static void main(String[] args)
{
int N = 12, K = 3;
System.out.println(KthLargestFactor(N, K));
}
}
Python
# Python program for the above approach
# Function to print Kth largest
# factor of N
def KthLargestFactor(N, K):
for i in range(N, 0, -1):
if N % i == 0:
K -= 1
if K == 0:
return i
return -1
# Driver Code
N = 12
K = 3
print(KthLargestFactor(N, K))
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to print Kth largest
// factor of N
static int KthLargestFactor(int N, int K)
{
// Check for numbers
// in the range [N, 1]
for (int i = N; i > 0; i--) {
// Check if i is a factor of N
if (N % i == 0)
// If Yes, reduce K by 1
K--;
// If K is 0, it means
// i is the required
// Kth factor of N
if (K == 0) {
return i;
}
}
// When K is more
// than the factors of N
return -1;
}
// Driver Code
public static void Main()
{
int N = 12, K = 3;
Console.Write(KthLargestFactor(N, K));
}
}
// This code is contributed by ipg2016107.
JavaScript
<script>
// JavaScript program for the above approach
// Function to print Kth largest
// factor of N
function KthLargestFactor(N, K)
{
// Check for numbers
// in the range [N, 1]
for (let i = N; i > 0; i--) {
// Check if i is a factor of N
if (N % i == 0)
// If Yes, reduce K by 1
K--;
// If K is 0, it means
// i is the required
// Kth factor of N
if (K == 0) {
return i;
}
}
// When K is more
// than the factors of N
return -1;
}
// Driver Code
let N = 12, K = 3;
document.write(KthLargestFactor(N, K));
// This code is contributed by shivanisinghss2110
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved in an optimized way in sqrt(n) complexity by using the fact that factors of any number remain in the form of pairs. In other words, if i is a factor of number n then n/i will also be a factor of n. So in order to find all the factors of the number we need to check for factors till sqrt(n) and their corresponding pairs. A similar type of approach is used in the article: find divisors of natural numbers.
Illustration:
If n = 80, then all the various pairs of divisors possible are: (1,80), (2,40), (4,20), (5,16), (8,10). Hence in order to store all the factors of 80, we will iterate the loop from 1 to √80 ≈ 8 and store the factors in the range(which includes 1,2,4,5,8 here in this case). After this, we run a reverse loop and store the pairs of these previous factors (which will give 10, 16, 20, 40, and 80). Here we are running a reverse loop so that we can get the pairs in increasing order. In this way, we will get all the factors which include {1, 2, 4, 5, 8, 10, 16, 20, 40, and 80}.
Approach:
- Initialize a vector to store the elements in increasing order.
- First, iterate a loop from 1 to sqrt(n) and store all the factors.
- Then iterate the loop in reverse order and for each factor store its corresponding pair. So if i is the factor then store n/i.
- If the size of the vector is greater or equal to k then return the kth largest factor(which will be v[v.size()-k] as the vector v is in increasing order).
- If k elements do not exist that means there is no kth largest factor and hence return -1.
Handling the corner cases:
A corner case will arise when any factor is exactly equal to sqrt(n). For example, if n=100, then in this case 10 will be a factor of the number, and also its corresponding pair is 10 as (10*10=100). So in this case 10 will be taken two times. In order to tackle this case, we use an if statement between two loops and remove the issue by considering this factor only one time.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to print Kth largest
// factor of N
int KthLargestFactor(int n, int k)
{
// vector v to store the factors
// of n in increasing order
vector<int> v;
int i;
// Iterating the loop and checking
// factors till sqrt(n)
for (i = 1; i * i <= n; i++) {
if (n % i == 0)
v.push_back(i);
}
// corner cases
if (i * i == n) {
i--;
}
for (; i >= 1; i--) {
if (n % i == 0)
v.push_back(n / i);
}
// When k is less than the factors
// of n then return the kth
// largest element which will be
// will kth element from the end
// in the vector
if (k <= v.size()) {
return v[v.size() - k];
}
// When k is more
// than the factors of n
else
return -1;
}
// Driver Code
int main()
{
int N = 12, K = 3;
cout << KthLargestFactor(N, K);
}
// This code is contributed by Pushpesh raj
Java
import java.io.*;
import java.util.*;
public class Main
{
// Function to print Kth largest
// factor of N
static int KthLargestFactor(int n, int k)
{
// vector v to store the factors
// of n in increasing order
ArrayList<Integer> v = new ArrayList<Integer>();
int i;
// Iterating the loop and checking
// factors till sqrt(n)
for (i = 1; i * i <= n; i++) {
if (n % i == 0)
v.add(i);
}
// corner cases
if (i * i == n) {
i--;
}
for (; i >= 1; i--) {
if (n % i == 0)
v.add(n / i);
}
// When k is less than the factors
// of n then return the kth
// largest element which will be
// will kth element from the end
// in the vector
if (k <= v.size()) {
return v.get(v.size() - k);
}
// When k is more
// than the factors of n
else
return -1;
}
public static void main(String[] args)
{
int N = 12, K = 3;
System.out.println(KthLargestFactor(N, K));
}
}
// This code is contributed by garg28harsh.
Python3
# Python program for the above approach
import math
# Function to prKth largest
# factor of N
def KthLargestFactor(n, k):
# vector v to store the factors
# of n in increasing order
v = []
# Iterating the loop and checking
# factors till sqrt(n)
i = 1
x = math.ceil(math.sqrt(n))
for j in range (1,x):
if (n % j == 0):
v.append(i)
i = j
# corner cases
if (i * i == n):
i-=1
# for ( i >= 1 i--) {
for j in range(i,0,-1):
if (n % i == 0):
v.append(math.floor(n / i))
# When k is less than the factors
# of n then return the kth
# largest element which will be
# will kth element from the end
# in the vector
if (k <= len(v)):
return v[len(v)- k]
# When k is more
# than the factors of n
else:
return -1
# Driver Code
N = 12
K = 3
print(KthLargestFactor(N, K))
# This code is contributed by akashish__
C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
// Function to print Kth largest
// factor of N
static int KthLargestFactor(int n, int k)
{
// vector v to store the factors
// of n in increasing order
ArrayList v = new ArrayList();
int i;
// Iterating the loop and checking
// factors till sqrt(n)
for (i = 1; i * i <= n; i++) {
if (n % i == 0)
v.Add(i);
}
// corner cases
if (i * i == n) {
i--;
}
for (; i >= 1; i--) {
if (n % i == 0)
v.Add(n / i);
}
// When k is less than the factors
// of n then return the kth
// largest element which will be
// will kth element from the end
// in the vector
if (k <= v.Count) {
return (int)v[v.Count - k];
}
// When k is more
// than the factors of n
else
return -1;
}
static public void Main()
{
// Code
int N = 12, K = 3;
Console.WriteLine(KthLargestFactor(N, K));
}
}
// This code is contributed by lokeshmvs21.
JavaScript
// Javascript program for the above approach
// Function to print Kth largest
// factor of N
function KthLargestFactor(n, k)
{
// vector v to store the factors
// of n in increasing order
var v=[];
var i;
// Iterating the loop and checking
// factors till sqrt(n)
for (i = 1; i * i <= n; i++) {
if (n % i == 0)
v.push(i);
}
// corner cases
if (i * i == n) {
i--;
}
for (; i >= 1; i--) {
if (n % i == 0)
v.push(n / i);
}
// When k is less than the factors
// of n then return the kth
// largest element which will be
// will kth element from the end
// in the vector
if (k <= v.length) {
return v[v.length - k];
}
// When k is more
// than the factors of n
else
return -1;
}
// Driver Code
var N = 12;
var K = 3;
console.log(KthLargestFactor(N, K));
// This code is contributed by Aman Kumar.
Time Complexity: O(sqrt(n))
Auxiliary Space: O(m) where m is the total number of factors of n.
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem