Count ways to express ā€˜nā€™ as sum of odd integers in C++


Given an integer n as input. The goal is to find the number of ways in which we can represent ‘n’ as the sum of odd integers. For example, if n is 3 it can be represented as sum ( 1+1+1 ) and (3) so total 2 ways.

For Example

Input

n=6

Output

Count of ways to express ‘n’ as sum of odd integers are: 8

Explanation

The ways in which we can express ‘n’ as sum of odd integers −
1. 1+1+1+1+1+1
2. 3+1+1+1
3. 1+3+1+1
4. 1+1+3+1
5. 1+1+1+3
6. 3+3
7. 1+5
8. 5+1

Input

n=9

Output

Count of ways to express ‘n’ as sum of odd integers are: 34

Explanation

The some of the ways in which we can express ‘n’ as sum of odd integers:
1. 1+1+1+1+1+1+1+1+1
2. 3+3+3
3. 5+3+1
4. 7+1+1
5. ….and other such combinations

Approach used in the below program is as follows

In this approach we will check the ways of representing a number as a sum of odd integers from previous numbers that are n−1th and n−2th numbers. Ways will be ways(n−1) + ways(n−2).

  • Take an integer n as input.

  • Function odd_ways(int n) takes a number and returns the count of ways to express ‘n’ as sum of odd integers.

  • Take an array arr of length n+1 to store count ways for representing numbers as sum of odd integers.

  • For number 0, there is no such way so set arr[0] with 0.

  • For number 1 there is only one way so set arr[1] with 1.

  • For the rest of numbers we can set arr[i] with arr[i−1]+arr[i−2] for i between 2 to n.

  • At the end we have arr[n] for the number of ways in which n is represented as the sum of odd integers.

  • Return arr[n] as result.

Example

 Live Demo

#include<iostream>
using namespace std;
int odd_ways(int n){
   int arr[n+1];
   arr[0] = 0;
   arr[1] = 1;
   for(int i = 2; i <= n; i++){
      arr[i] = arr[i-1] + arr[i-2];
   }
   return arr[n];
}
int main(){
   int n = 6;
   cout<<"Count of ways to express ‘n’ as sum of odd integers are: "<<odd_ways(n);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of ways to express ‘n’ as sum of odd integers are: 8

Updated on: 05-Jan-2021

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements