Find politeness of a number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a positive integer N. Our task is to find the politeness of a number.

Polite Number is a number which can be expressed as a sum of two or more consecutive numbers.

Politeness of a number is defined as the number of ways the number can be expressed as sum of consecutive integers.

Let’s take an example to understand the problem,

Input

n = 5

Output

1

Explanation

2 + 3 = 5, is the only consecutive sum.

Solution Approach

A simple solution to the problem is to check all consecutive numbers till N and if their sum is equal to N, increase count which is the politeness of the number.

This solution is not efficient but a complicated but efficient solution is using factorisation. Using the formula for politeness that happens to be product of count of odd factors i.e.

If the number is represented as
N = ax * by * cz…
Politeness = [(x + 1)*(y +1)*(z + 1)... ] - 1

Program to illustrate the working of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
int calcPolitenessNumber(int n){
   int politeness = 1;
   while (n % 2 == 0)
      n /= 2;
   for (int i = 3; i * i <= n; i += 2) {
      int divCount = 0;
      while (n % i == 0) {
         n /= i;
         ++divCount;
      }
      politeness *= divCount + 1;
   }
   if (n > 2)
      politeness *= 2;
      return (politeness - 1);
}
int main(){
   int n = 13;
   cout<<"Politeness of "<<n<<" is "<<calcPolitenessNumber(n);
   return 0;
}

Output

Politeness of 13 is 1
raja
Published on 16-Mar-2021 05:08:11
Advertisements