Check whether a number can be represented as sum of K distinct positive integers
Last Updated :
20 Sep, 2023
Given two integers N and K, the task is to check whether N can be represented as sum of K distinct positive integers.
Examples:
Input: N = 12, K = 4
Output: Yes
N = 1 + 2 + 4 + 5 = 12 (12 as sum of 4 distinct integers)
Input: N = 8, K = 4
Output: No
Approach: Consider the series 1 + 2 + 3 + ... + K which has exactly K distinct integers with minimum possible sum i.e. Sum = (K * (K - 1)) / 2. Now, if N < Sum then it is not possible to represent N as the sum of K distinct positive integers but if N ≥ Sum then any integer say X ≥ 0 can be added to Sum to generate the sum equal to N i.e. 1 + 2 + 3 + ... + (K - 1) + (K + X) ensuring that there are exactly K distinct positive integers.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <iostream>
using namespace std;
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
bool solve(int n, int k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
int main()
{
int n = 12, k = 4;
if (solve(n, k))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java implementation of the approach
import java.io.*;
class GFG {
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
static boolean solve(int n, int k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
public static void main(String[] args)
{
int n = 12, k = 4;
if (solve(n, k))
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by anuj_67..
Python3
# Python 3 implementation of the approach
# Function that returns true if n
# can be represented as the sum of
# exactly k distinct positive integers
def solve(n,k):
# If n can be represented as
# 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) // 2):
return True
return False
# Driver code
if __name__ == '__main__':
n = 12
k = 4
if (solve(n, k)):
print("Yes")
else:
print("No")
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
static bool solve(int n, int k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
static public void Main ()
{
int n = 12, k = 4;
if (solve(n, k))
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
// This code is contributed by ajit.
JavaScript
<script>
// Javascript implementation of the approach
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
function solve(n, k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if (n >= (k * (k + 1)) / 2)
{
return true;
}
return false;
}
// Driver code
var n = 12, k = 4;
if (solve(n, k))
document.write("Yes");
else
document.write("No");
// This code is contributed by todaysgaurav
</script>
PHP
<?php
// PHP implementation of the approach
// Function that returns true if n
// can be represented as the sum of
// exactly k distinct positive integers
function solve($n, $k)
{
// If n can be represented as
// 1 + 2 + 3 + ... + (k - 1) + (k + x)
if ($n >= ($k * ($k + 1)) / 2) {
return true;
}
return false;
}
// Driver code
$n = 12;
$k = 4;
if (solve($n, $k))
echo "Yes";
else
echo "No";
// This code is contributed by ihritik
?>
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach 2: Dynamic Programming:
Here's the dynamic programming (DP) approach to solve the same problem:
- Define a 2D array dp of size (n+1) x (k+1).
- Initialize dp[i][j] to false if either i is 0 or j is 0, and to true if j is 1.
- For i from 1 to n and j from 2 to k, do the following steps:
- a. If i >= j, then set dp[i][j] to dp[i-1][j] || dp[i-j][j-1].
- b. If i < j, then set dp[i][j] to dp[i-1][j].
- If dp[n][k] is true, return true, else return false.
- Here's the C++ code for the above DP approach:
C++
#include <iostream>
#include <vector>
using namespace std;
bool canSumToDistinctIntegers(int n, int k) {
vector<vector<bool>> dp(n+1, vector<bool>(k+1, false));
for (int i = 0; i <= n; i++) {
dp[i][0] = false;
}
for (int j = 0; j <= k; j++) {
dp[0][j] = false;
}
for (int j = 1; j <= k; j++) {
dp[1][j] = true;
}
for (int i = 1; i <= n; i++) {
for (int j = 2; j <= k; j++) {
if (i >= j) {
dp[i][j] = dp[i-1][j] || dp[i-j][j-1];
}
else {
dp[i][j] = dp[i-1][j];
}
}
}
return dp[n][k];
}
int main() {
int n = 12, k = 4;
if (canSumToDistinctIntegers(n, k)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
Java
public class GFG {
public static boolean canSumToDistinctIntegers(int n, int k) {
// Create a 2D DP array to store the results of subproblems
boolean[][] dp = new boolean[n + 1][k + 1];
// Initialize base cases
for (int i = 0; i <= n; i++) {
dp[i][0] = false;
}
for (int j = 0; j <= k; j++) {
dp[0][j] = false;
}
for (int j = 1; j <= k; j++) {
dp[1][j] = true;
}
// Fill the DP array bottom-up
for (int i = 1; i <= n; i++) {
for (int j = 2; j <= k; j++) {
if (i >= j) {
dp[i][j] = dp[i - 1][j] || dp[i - j][j - 1];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n][k];
}
public static void main(String[] args) {
int n = 12, k = 4;
// Check if it is possible to form a sum of k distinct integers
if (canSumToDistinctIntegers(n, k)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python3
def can_sum_to_distinct_integers(n, k):
# Create a 2D DP table with n+1 rows and k+1 columns, initialized with False values
dp = [[False] * (k+1) for _ in range(n+1)]
# Base case: If k is 0, it is always possible to form an empty set, so set dp[i][0] to True for all i.
for i in range(n+1):
dp[i][0] = False
# Base case: If n is 0, it is not possible to form a set with any sum, so set dp[0][j] to False for all j.
for j in range(k+1):
dp[0][j] = False
# Base case: If k is 1, it is always possible to form a set with just one element equal to n,
# so set dp[1][j] to True for all j.
for j in range(1, k+1):
dp[1][j] = True
# Fill the DP table using bottom-up approach
for i in range(1, n+1):
for j in range(2, k+1):
if i >= j:
# If the current number i is greater than or equal to j,
# we have two options: include i or exclude i to form the sum j.
# dp[i-1][j] represents excluding i, and dp[i-j][j-1] represents including i.
dp[i][j] = dp[i-1][j] or dp[i-j][j-1]
else:
# If the current number i is less than j, we can only exclude i to form the sum j.
dp[i][j] = dp[i-1][j]
# The final result is stored in dp[n][k], which represents whether it is possible to form a set of k distinct integers
# whose sum is n.
return dp[n][k]
# Driver code
n = 12
k = 4
if can_sum_to_distinct_integers(n, k):
print("YES")
else:
print("No")
C#
using System;
public class GFG
{
public static bool CanSumToDistinctIntegers(int n, int k)
{
// Create a 2D DP array to store the results of subproblems
bool[,] dp = new bool[n + 1, k + 1];
// Initialize base cases
for (int i = 0; i <= n; i++)
{
dp[i, 0] = false;
}
for (int j = 0; j <= k; j++)
{
dp[0, j] = false;
}
for (int j = 1; j <= k; j++)
{
dp[1, j] = true;
}
// Fill the DP array bottom-up
for (int i = 1; i <= n; i++)
{
for (int j = 2; j <= k; j++)
{
if (i >= j)
{
dp[i, j] = dp[i - 1, j] || dp[i - j, j - 1];
}
else
{
dp[i, j] = dp[i - 1, j];
}
}
}
return dp[n, k];
}
public static void Main()
{
int n = 12, k = 4;
// Check if it is possible to form a sum of k distinct integers
if (CanSumToDistinctIntegers(n, k))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
// To pause the console before exiting
Console.ReadLine();
}
}
JavaScript
// This function determines if it is possible to represent a given integer n
// as the sum of k distinct positive integers
function canSumToDistinctIntegers(n, k) {
// Create a 2D array to store the DP table, with n+1 rows and k+1 columns
let dp = new Array(n+1);
for (let i = 0; i <= n; i++) {
dp[i] = new Array(k+1).fill(false);
}
// Set base cases
for (let i = 0; i <= n; i++) {
dp[i][0] = false;
}
for (let j = 0; j <= k; j++) {
dp[0][j] = false;
}
for (let j = 1; j <= k; j++) {
dp[1][j] = true;
}
// Fill in the DP table using a nested loop
for (let i = 1; i <= n; i++) {
for (let j = 2; j <= k; j++) {
if (i >= j) {
dp[i][j] = dp[i-1][j] || dp[i-j][j-1];
}
else {
dp[i][j] = dp[i-1][j];
}
}
}
// Return the result, which is stored in the last cell of the DP table
return dp[n][k];
}
// Test the function with some sample input
let n = 12, k = 4;
if (canSumToDistinctIntegers(n, k)) {
console.log("Yes");
}
else {
console.log("No");
}
Output:
Yes
Time Complexity: O(nk), where n is the maximum possible value of n (the input number), and k is the maximum possible value of k
Auxiliary Space: O(nk) because we need to store the intermediate results in a 2D array.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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