C++ code to count number of weight splits of a number n

C++Server Side ProgrammingProgramming

Suppose we have a number n. We can split n as a nonincreasing sequence of positive integers, whose sum is n. The weight of a split is the number of elements in the split that are equal to the first element. So, the weight of the split [1,1,1,1,1] is 5, the weight of the split [5,5,3,3,3] is 2 and the weight of the split [9] equals 1. We have to find out the number of different weights of n's splits.

So, if the input is like n = 7, then the output will be 4, because possible weights are [7], [3, 3, 1], [2, 2, 2, 1], [1, 1, 1, 1, 1, 1, 1]

Steps

To solve this, we will follow these steps −

return (n / 2 + 1)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int n){
   return (n / 2 + 1);
}
int main(){
   int n = 7;
   cout << solve(n) << endl;
}

Input

7

Output

4
raja
Updated on 30-Mar-2022 12:51:28

Advertisements