Find Landau's function for a given number N
Last Updated :
15 Jul, 2025
Given an integer N, the task is to find the Landau's Function of the number N.
In number theory, The Landau's function finds the largest LCM among all partitions of the given number N.
For Example: If N = 4, then possible partitions are:
1. {1, 1, 1, 1}, LCM = 1
2. {1, 1, 2}, LCM = 2
3. {2, 2}, LCM = 2
4. {1, 3}, LCM = 3
Among the above partitions, the partitions whose LCM is maximum is {1, 3} as LCM = 3.
Examples:
Input: N = 4
Output: 4
Explanation:
Partitions of 4 are [1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4] among which maximum LCM is of the last partition 4 whose LCM is also 4.
Input: N = 7
Output: 12
Explanation:
For N = 7 the maximum LCM is 12.
A slower (but easier to understand) algorithm
Approach: The idea is to use Recursion to generate all possible partitions for the given number N and find the maximum value of LCM among all the partitions. Consider every integer from 1 to N such that the sum N can be reduced by this number at each recursive call and if at any recursive call N reduces to zero then find the LCM of the value stored in the vector. Below are the steps for recursion:
- Get the number N whose sum has to be broken into two or more positive integers.
- Recursively iterate from value 1 to N as index i:
- Base Case: If the value called recursively is 0, then find the LCM of the value stored in the current vector as this is the one of the way to broke N into two or more positive integers.
if (n == 0)
findLCM(arr);
- Recursive Call: If the base case is not met, then Recursively iterate from [i, N - i]. Push the current element j into vector(say arr) and recursively iterate for the next index and after the this recursion ends then pop the element j inserted previously:
for j in range[i, N]:
arr.push_back(j);
recursive_function(arr, j + 1, N - j);
arr.pop_back(j);
- After all the recursive call, print the maximum of all the LCM calculated.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// To store Landau's function of the number
int Landau = INT_MIN;
// Function to return gcd of 2 numbers
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to return LCM of two numbers
int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
// Function to find max lcm value
// among all representations of n
void findLCM(vector<int>& arr)
{
int nth_lcm = arr[0];
for (int i = 1; i < arr.size(); i++)
nth_lcm = lcm(nth_lcm, arr[i]);
// Calculate Landau's value
Landau = max(Landau, nth_lcm);
}
// Recursive function to find different
// ways in which n can be written as
// sum of atleast one positive integers
void findWays(vector<int>& arr, int i, int n)
{
// Check if sum becomes n,
// consider this representation
if (n == 0)
findLCM(arr);
// Start from previous element
// in the representation till n
for (int j = i; j <= n; j++) {
// Include current element
// from representation
arr.push_back(j);
// Call function again
// with reduced sum
findWays(arr, j, n - j);
// Backtrack - remove current
// element from representation
arr.pop_back();
}
}
// Function to find the Landau's function
void Landau_function(int n)
{
vector<int> arr;
// Using recurrence find different
// ways in which n can be written
// as a sum of atleast one +ve integers
findWays(arr, 1, n);
// Print the result
cout << Landau;
}
// Driver Code
int main()
{
// Given N
int N = 4;
// Function Call
Landau_function(N);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG{
// To store Landau's function of the number
static int Landau = Integer.MIN_VALUE;
// Function to return gcd of 2 numbers
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to return LCM of two numbers
static int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
// Function to find max lcm value
// among all representations of n
static void findLCM(Vector<Integer> arr)
{
int nth_lcm = arr.get(0);
for(int i = 1; i < arr.size(); i++)
nth_lcm = lcm(nth_lcm, arr.get(i));
// Calculate Landau's value
Landau = Math.max(Landau, nth_lcm);
}
// Recursive function to find different
// ways in which n can be written as
// sum of atleast one positive integers
static void findWays(Vector<Integer> arr,
int i, int n)
{
// Check if sum becomes n,
// consider this representation
if (n == 0)
findLCM(arr);
// Start from previous element
// in the representation till n
for(int j = i; j <= n; j++)
{
// Include current element
// from representation
arr.add(j);
// Call function again
// with reduced sum
findWays(arr, j, n - j);
// Backtrack - remove current
// element from representation
arr.remove(arr.size() - 1);
}
}
// Function to find the Landau's function
static void Landau_function(int n)
{
Vector<Integer> arr = new Vector<>();
// Using recurrence find different
// ways in which n can be written
// as a sum of atleast one +ve integers
findWays(arr, 1, n);
// Print the result
System.out.print(Landau);
}
// Driver Code
public static void main(String[] args)
{
// Given N
int N = 4;
// Function call
Landau_function(N);
}
}
// This code is contributed by amal kumar choubey
Python3
# Python3 program for the above approach
import sys
# To store Landau's function of the number
Landau = -sys.maxsize - 1
# Function to return gcd of 2 numbers
def gcd(a, b):
if (a == 0):
return b
return gcd(b % a, a)
# Function to return LCM of two numbers
def lcm(a, b):
return (a * b) // gcd(a, b)
# Function to find max lcm value
# among all representations of n
def findLCM(arr):
global Landau
nth_lcm = arr[0]
for i in range(1, len(arr)):
nth_lcm = lcm(nth_lcm, arr[i])
# Calculate Landau's value
Landau = max(Landau, nth_lcm)
# Recursive function to find different
# ways in which n can be written as
# sum of atleast one positive integers
def findWays(arr, i, n):
# Check if sum becomes n,
# consider this representation
if (n == 0):
findLCM(arr)
# Start from previous element
# in the representation till n
for j in range(i, n + 1):
# Include current element
# from representation
arr.append(j)
# Call function again
# with reduced sum
findWays(arr, j, n - j)
# Backtrack - remove current
# element from representation
arr.pop()
# Function to find the Landau's function
def Landau_function(n):
arr = []
# Using recurrence find different
# ways in which n can be written
# as a sum of atleast one +ve integers
findWays(arr, 1, n)
# Print the result
print(Landau)
# Driver Code
# Given N
N = 4
# Function call
Landau_function(N)
# This code is contributed by chitranayal
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG{
// To store Landau's function of the number
static int Landau = int.MinValue;
// Function to return gcd of 2 numbers
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to return LCM of two numbers
static int lcm(int a, int b)
{
return (a * b) / gcd(a, b);
}
// Function to find max lcm value
// among all representations of n
static void findLCM(List<int> arr)
{
int nth_lcm = arr[0];
for(int i = 1; i < arr.Count; i++)
nth_lcm = lcm(nth_lcm, arr[i]);
// Calculate Landau's value
Landau = Math.Max(Landau, nth_lcm);
}
// Recursive function to find different
// ways in which n can be written as
// sum of atleast one positive integers
static void findWays(List<int> arr,
int i, int n)
{
// Check if sum becomes n,
// consider this representation
if (n == 0)
findLCM(arr);
// Start from previous element
// in the representation till n
for(int j = i; j <= n; j++)
{
// Include current element
// from representation
arr.Add(j);
// Call function again
// with reduced sum
findWays(arr, j, n - j);
// Backtrack - remove current
// element from representation
arr.RemoveAt(arr.Count - 1);
}
}
// Function to find the Landau's function
static void Landau_function(int n)
{
List<int> arr = new List<int>();
// Using recurrence find different
// ways in which n can be written
// as a sum of atleast one +ve integers
findWays(arr, 1, n);
// Print the result
Console.Write(Landau);
}
// Driver Code
public static void Main(String[] args)
{
// Given N
int N = 4;
// Function call
Landau_function(N);
}
}
// This code is contributed by amal kumar choubey
JavaScript
<script>
// Javascript program for the above approach
// To store Landau's function of the number
var Landau = -1000000000;
// Function to return gcd of 2 numbers
function gcd(a, b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
// Function to return LCM of two numbers
function lcm(a, b)
{
return (a * b) / gcd(a, b);
}
// Function to find max lcm value
// among all representations of n
function findLCM(arr)
{
var nth_lcm = arr[0];
for (var i = 1; i < arr.length; i++)
nth_lcm = lcm(nth_lcm, arr[i]);
// Calculate Landau's value
Landau = Math.max(Landau, nth_lcm);
}
// Recursive function to find different
// ways in which n can be written as
// sum of atleast one positive integers
function findWays(arr, i, n)
{
// Check if sum becomes n,
// consider this representation
if (n == 0)
findLCM(arr);
// Start from previous element
// in the representation till n
for (var j = i; j <= n; j++) {
// Include current element
// from representation
arr.push(j);
// Call function again
// with reduced sum
findWays(arr, j, n - j);
// Backtrack - remove current
// element from representation
arr.pop();
}
}
// Function to find the Landau's function
function Landau_function(n)
{
arr = [];
// Using recurrence find different
// ways in which n can be written
// as a sum of atleast one +ve integers
findWays(arr, 1, n);
// Print the result
document.write( Landau);
}
// Driver Code
// Given N
var N = 4;
// Function Call
Landau_function(N);
// This code is contributed by rrrtnx.
</script>
Time Complexity: O(2N)
Auxiliary Space: O(N2)
A faster algorithm
Lemma. There is an optimal answer where every number in partition is either 1 or of form p^a, where p is prime.
Proof. Suppose that in an optimal partition we have some n which has more than one prime factors. Then we can write n=mk, where gcd(m, k) = 1 and m>1 and k>1. Here we should note than mk \geq m+k, so (mk - m - k) \geq 0. So let's remove n from partition and replace it with m and k and (mk - m - k) 1's (example : [..., 12, ...] -> [..., 3 4 1 1 1 1 1, ...]). The sum of the array hasn't changed, so it is still a partition of n, and the lcm, obviously, hasn't changed. So it is still an optimal partition. We do that replacement several times until there is no number with >1 prime factors. QED
Lets define a function g(n, p), where n is prime, as the optimal answer where all numbers only consist of primes which are less than p. (Example: g(4, 3) = 4. The optimal answer is [2^2]. Note that the answer [2, 3] doesn't count since 3\geq p). Let's also say that g(0, p) = 1 and g(n, 2) = 1 so it's a bit easier for us.
Then we can write a recursive formula for g(n, p):
g(n, p) is maximum of:
- g(n, prev. prime of p) - we add nothing and restrict all next primes to be less than prev. prime of p
- g(n - p, prev. prime of p)*p - we add p and restrict all next primes to be less than prev. prime of p
- g(n - p^2, prev. prime of p)*p^2 - we add p^2 and restrict all next primes to be less than prev. prime of p
- g(n - p^3, prev. prime of p)*p^3 - we add p^3 and restrict all next primes to be less than prev. prime of p
- etc...
So g(n, min prime which is >n) is our answer. We can get the answer by using dynamic programming.
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n = 4;
vector<int> primes;
vector<int> max_prime(2 * n + 1, 0);
for (int i = 2; i <= 2 * n; ++i) {
if (max_prime[i] == 0) {
max_prime[i] = i;
primes.push_back(i);
}
for (int j = 0;
j < primes.size() && primes[j] <= max_prime[i]
&& 1ll * primes[j] * i <= 2 * n;
++j) {
max_prime[primes[j] * i] = max_prime[i];
}
}
vector<vector<long long> > g(
n + 1, vector<long long>(primes.size() + 1, 1ll));
for (int p = 1; p <= primes.size(); ++p) {
for (int i = 0; i <= n; ++i) {
g[i][p] = g[i][p - 1];
long long power = primes[p - 1];
while (power <= i) {
long long new_option
= g[i - power][p - 1] * power;
g[i][p] = max(g[i][p], new_option);
power *= primes[p - 1];
}
}
}
cout << g[n][primes.size()] << endl;
return 0;
}
Java
import java.util.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
int n = 4;
List<Integer> primes = new ArrayList<>();
int[] maxPrime = new int[2 * n + 1];
Arrays.fill(maxPrime, 0);
for (int i = 2; i <= 2 * n; ++i) {
if (maxPrime[i] == 0) {
maxPrime[i] = i;
primes.add(i);
}
for (int j = 0; j < primes.size() && primes.get(j) <= maxPrime[i]
&& (long) primes.get(j) * i <= 2 * n; ++j) {
maxPrime[primes.get(j) * i] = maxPrime[i];
}
}
long[][] g = new long[n + 1][primes.size() + 1];
for (int i = 0; i <= n; ++i) {
Arrays.fill(g[i], 1);
}
for (int p = 1; p <= primes.size(); ++p) {
for (int i = 0; i <= n; ++i) {
g[i][p] = g[i][p - 1];
int power = primes.get(p - 1);
while (power <= i) {
long newOption = g[i - power][p - 1] * power;
g[i][p] = Math.max(g[i][p], newOption);
power *= primes.get(p - 1);
}
}
}
System.out.println(g[n][primes.size()]);
}
}
Python3
import math
n = 4
primes = []
max_prime = [0] * (2 * n + 1)
for i in range(2, 2 * n + 1):
if max_prime[i] == 0:
max_prime[i] = i;
primes.append(i);
j = 0
while j < len(primes) and primes[j] <= max_prime[i] and primes[j] * i <= 2 * n:
max_prime[primes[j] * i] = max_prime[i]
j += 1
g = [[1 for i in range(len(primes) + 1)] for j in range(n + 1)]
for p in range(1, len(primes) + 1):
for i in range(0, n + 1):
g[i][p] = g[i][p - 1]
power = primes[p - 1]
while power <= i:
new_option = g[i - power][p - 1] * power;
g[i][p] = max(g[i][p], new_option);
power *= primes[p - 1];
print(g[n][len(primes)])
C#
// Importing required libraries
using System;
using System.Collections.Generic;
// Defining the main class
class MainClass {
static void Main()
{
// Initializing the value of n
int n = 4; // Declaring and initializing the lists
List<int> primes = new List<int>();
List<int> max_prime = new List<int>();
for (int i = 0; i <= 2 * n; ++i) {
max_prime.Add(0);
}
// Finding the prime numbers
for (int i = 2; i <= 2 * n; ++i) {
if (max_prime[i] == 0) {
max_prime[i] = i;
primes.Add(i);
}
for (int j = 0; j < primes.Count
&& primes[j] <= max_prime[i]
&& 1L * primes[j] * i <= 2 * n;
++j) {
max_prime[primes[j] * i] = max_prime[i];
}
}
// Initializing the 2D list with all values as 1
List<List<long> > g = new List<List<long> >();
for (int i = 0; i <= n; ++i) {
List<long> row = new List<long>();
for (int j = 0; j <= primes.Count; ++j) {
row.Add(1L);
}
g.Add(row);
}
// Finding the maximum product of primes such that
// the sum of the primes is n
for (int p = 1; p <= primes.Count; ++p) {
for (int i = 0; i <= n; ++i) {
g[i][p] = g[i][p - 1];
long power = primes[p - 1];
while (power <= i) {
long new_option
= g[i - (int)power][p - 1] * power;
g[i][p] = Math.Max(g[i][p], new_option);
power *= primes[p - 1];
}
}
}
// Printing the maximum product of primes such that
// the sum of the primes is n
Console.WriteLine(g[n][primes.Count]);
}
}
JavaScript
// Import required libraries
// None needed in JavaScript
// Define the main function
function main() {
const n = 4;
const primes = [];
const maxPrime = new Array(2 * n + 1).fill(0);
// Calculate the maximum prime factor for each number between 2 and 2n
for (let i = 2; i <= 2 * n; ++i) {
if (maxPrime[i] === 0) {
maxPrime[i] = i;
primes.push(i);
}
for (let j = 0; j < primes.length && primes[j] <= maxPrime[i] &&
primes[j] * i <= 2 * n; ++j) {
maxPrime[primes[j] * i] = maxPrime[i];
}
}
// Create a 2D array g to store the maximum product for each i and j
const g = new Array(n + 1).fill().map(() => new Array(primes.length + 1).fill(1));
// Fill in the g array
for (let p = 1; p <= primes.length; ++p) {
for (let i = 0; i <= n; ++i) {
g[i][p] = g[i][p - 1];
let power = primes[p - 1];
while (power <= i) {
const newOption = g[i - power][p - 1] * power;
g[i][p] = Math.max(g[i][p], newOption);
power *= primes[p - 1];
}
}
}
// Print the maximum product for n
console.log(g[n][primes.length]);
}
// Call the main function to run the program
main();
Time complexity: O(N^2 / logN)
Proof. We use the fact that there are approx n/logn primes less than n and that log(sqrt(n)) = 1/2 log(n). For primes that are <= sqrt(N), we check no more than log2(N) powers. So the time complexity for these primes is O(N * (sqrtN/0.5log(N)) * logN) = O(N * sqrtN)
For primes that are > sqrt(N), we check exactly one power. So the time complexity for these primes is O(N * (N/logN - sqrtN / 0.5logN) * 1) = O(N * N / logN) = O(N^2 / logN).
So the time complexity is O(NsqrtN + N^2/logN) = O(N^2/logN). QED
Space complexity: O(N^2 / logN).
It should be noted that for large enough n you can't use standard integer types to get the answer. Instead, you should use long arithmetic. For multiplying you could use, for example, FFT.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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