Saturday, November 16, 2024
Google search engine
HomeData Modelling & AIFind politeness of a number

Find politeness of a number

Given an integer n. Find politeness of number n. The politeness of a number is defined as the number of ways it can be expressed as the sum of consecutive integers. 

Examples:

Input: n = 15
Output: 3
Explanation:
There are only three ways to express
15 as sum of consecutive integers i.e.,
15 = 1 + 2 + 3 + 4 + 5
15 = 4 + 5 + 6
15 = 7 + 8
Hence answer is 3

Input: n = 9;
Output: 2
There are two ways of representation:
9 = 2 + 3 + 4
9 = 4 + 5
We strongly recommend that you click here and practice it, before moving on to the solution.

Naive approach:

Run a loop one inside another and find the sum of every consecutive integer up to n. The time complexity of this approach will be O(n2) which will not be sufficient for large value of n.

Efficient Approach:

Use factorization. We factorize the number n and count the number of odd factors. A total number of odd factors (except 1) is equal to the politeness of the number. Refer this for proof of this fact. In general, if a number can be represented as ap * bq * cr … where a, b, c, … are prime factors of n. If a = 2 (even) then discard it and count total number of odd factors which can be written as [(q + 1) * (r + 1) * …] – 1 (Here 1 is subtracted because single term in representation is not allowed). 
How does the above formula work? The fact is if a number is expressed as ap * bq * cr … where a, b, c, … are prime factors of n, then a number of divisors is (p+1)*(q+1)*(r+1) …… 
To simplify, let there be one factor, and the number is expressed as ap. Divisors are 1, a, a2, …. ap. The count of divisors is p+1. Now let us take a slightly more complicated case apbp. The divisors are : 
1, a, a2, …. ap 
b, ba, ba2, …. bap 
b2, b2a, b2a2, …. b2ap 
……………. 
……………. 
bq, bqa, bqa2, …. bqap
The count of the above terms is (p+1)*(q+1). Similarly, we can prove for more prime factors.
Illustration : For n = 90, decomposition of prime factors will be as follows:- 
=> 90 = 2 * 32 * 51. The power of odd prime factors 3, 5 are 2 and 1 respectively. Apply above formula as: (2 + 1) * (1 + 1) -1 = 5. Hence 5 will be the answer. We can crosscheck it. All odd factors are 3, 5, 9, 15 and 45.
Below is the program of the above steps:

C++




// C+ program to find politeness of number
#include <iostream>
using namespace std;
 
// A function to count all odd prime factors
// of a given number n
int countOddPrimeFactors(int n)
{
    int result = 1;
 
    // Eliminate all even prime
    // factor of number of n
    while (n % 2 == 0)
        n /= 2;
 
    // n must be odd at this point,
    // so iterate for only
    // odd numbers till sqrt(n)
    for (int i = 3; i * i <= n; i += 2) {
        int divCount = 0;
 
        // if i divides n, then start counting of
        // Odd divisors
        while (n % i == 0) {
            n /= i;
            ++divCount;
        }
 
        result *= divCount + 1;
    }
 
    // If n odd prime still remains then count it
    if (n > 2)
        result *= 2;
 
    return result;
}
 
int politeness(int n)
{
    return countOddPrimeFactors(n) - 1;
}
 
// Driver program to test above function
int main()
{
    int n = 90;
    cout << "Politeness of " << n << " = "
         << politeness(n) << "\n";
 
    n = 15;
    cout << "Politeness of " << n << " = "
         << politeness(n) << "\n";
    return 0;
}


Java




// Java program to find politeness of a number
 
public class Politeness {
    // A function to count all odd prime factors
    // of a given number n
    static int countOddPrimeFactors(int n)
    {
        int result = 1;
 
        // Eliminate all even prime
        // factor of number of n
        while (n % 2 == 0)
            n /= 2;
 
        // n must be odd at this point, so iterate
        // for only odd numbers till sqrt(n)
        for (int i = 3; i * i <= n; i += 2) {
            int divCount = 0;
 
            // if i divides n, then start counting of
            // Odd divisors
            while (n % i == 0) {
                n /= i;
                ++divCount;
            }
 
            result *= divCount + 1;
        }
        // If n odd prime still remains then count it
        if (n > 2)
            result *= 2;
 
        return result;
    }
 
    static int politeness(int n)
    {
        return countOddPrimeFactors(n) - 1;
    }
 
    public static void main(String[] args)
    {
        int n = 90;
        System.out.println("Politeness of " + n + " = "
                           + politeness(n));
 
        n = 15;
        System.out.println("Politeness of " + n + " = "
                           + politeness(n));
    }
}
 
// This code is contributed by Saket Kumar


Python3




# Python program to find politeness of number
 
# A function to count all odd prime factors
# of a given number n
def countOddPrimeFactors(n) :
    result = 1;
  
    # Eliminate all even prime factor of
    # number of n
    while (n % 2 == 0) :
        n //= 2
  
    # n must be odd at this point, so iterate
    # for only odd numbers till sqrt(n)
    i = 3
    while i * i <= n :
        divCount = 0
  
        # if i divides n, then start counting
        # of Odd divisors
        while (n % i == 0) :
            n //= i
            divCount = divCount + 1
        
        result = result * divCount + 1
        i = i + 2
  
    # If n odd prime still remains then count it
    if (n > 2) :
        result = result * 2
         
    return result
     
  
def politeness( n) :
    return countOddPrimeFactors(n) - 1;
 
# Driver program to test above function
n = 90
print ("Politeness of ", n, " = ", politeness(n))
n = 15
print ("Politeness of ", n, " = ", politeness(n))
 
# This code is contributed by Nikita Tiwari.


C#




// C# program to find politeness of a number.
using System;
 
public class GFG {
     
    // A function to count all odd prime
    // factors of a given number n
    static int countOddPrimeFactors(int n)
    {
         
        int result = 1;
 
        // Eliminate all even prime factor
        // of number of n
        while (n % 2 == 0)
            n /= 2;
 
        // n must be odd at this point, so
        // iterate for only odd numbers
        // till sqrt(n)
        for (int i = 3; i * i <= n; i += 2)
        {
            int divCount = 0;
 
            // if i divides n, then start
            // counting of Odd divisors
            while (n % i == 0) {
                n /= i;
                ++divCount;
            }
 
            result *= divCount + 1;
        }
         
        // If n odd prime still remains
        // then count it
        if (n > 2)
            result *= 2;
 
        return result;
    }
 
    static int politeness(int n)
    {
        return countOddPrimeFactors(n) - 1;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 90;
        Console.WriteLine("Politeness of "
               + n + " = " + politeness(n));
 
        n = 15;
        Console.WriteLine("Politeness of "
               + n + " = " + politeness(n));
    }
}
 
// This code is contributed by nitin mittal.


Javascript




<script>
// JavaScript program for the above approach
  
    // A function to count all odd prime
    // factors of a given number n
    function countOddPrimeFactors(n)
    {
          
        let result = 1;
  
        // Eliminate all even prime factor
        // of number of n
        while (n % 2 == 0)
            n /= 2;
  
        // n must be odd at this point, so
        // iterate for only odd numbers
        // till sqrt(n)
        for (let i = 3; i * i <= n; i += 2)
        {
            let divCount = 0;
  
            // if i divides n, then start
            // counting of Odd divisors
            while (n % i == 0) {
                n /= i;
                ++divCount;
            }
  
            result *= divCount + 1;
        }
          
        // If n odd prime still remains
        // then count it
        if (n > 2)
            result *= 2;
  
        return result;
    }
  
    function politeness(n)
    {
        return countOddPrimeFactors(n) - 1;
    }
 
// Driver Code
     let n = 90;
        document.write("Politeness of "
               + n + " = " + politeness(n) + "<br />");
  
        n = 15;
        document.write("Politeness of "
               + n + " = " + politeness(n));
 
// This code is contributed by splevel62.
</script>


PHP




<?php
// PHP program to find
// politeness of number
 
// A function to count all
// odd prime factors of a
// given number n
function countOddPrimeFactors($n)
{
    $result = 1;
 
    // Eliminate all even prime
    // factor of number of n
    while($n % 2 == 0)
        $n /= 2;
 
    // n must be odd at this
    // point, so iterate for only
    // odd numbers till sqrt(n)
    for ($i = 3; $i * $i <= $n; $i += 2)
    {
        $divCount = 0;
 
        // if i divides n, then
        // start counting of
        // Odd divisors
        while($n % $i == 0)
        {
            $n /= $i;
            ++$divCount;
        }
 
        $result *= $divCount + 1;
    }
 
    // If n odd prime still
    // remains then count it
    if ($n > 2)
        $result *= 2;
 
    return $result;
}
 
function politeness($n)
{
    return countOddPrimeFactors($n) - 1;
}
 
    // Driver Code
    $n = 90;
    echo "Politeness of " , $n , " = "
               , politeness($n), "\n";
 
    $n = 15;
    echo "Politeness of " , $n , " = "
               , politeness($n) ,"\n";
 
// This code is contributed by nitin mittal.
?>


Output:
Politeness of 90 = 5
Politeness of 15 = 3

Time complexity: O(sqrt(n)) 
Auxiliary space: O(1)
Reference: Wikipedia

Another Efficient approach:

Calculate if an AP can be generated for the given length domain [2, sqrt(2*n)]. The reason to calculate for length till sqrt(2*n) is-

max length will be for the AP 1, 2, 3…

Length for this AP is -

n= ( len * (len+1) ) / 2

len2 + len - (2*n) =0

so len≈sqrt(2*n)

so we can check for each len from 1 to sqrt(2*n) ,if AP can be generated with this len. The formula to get the first term of the AP is –

n= ( len/2) * ( (2*A1) + len-1 )

Below is the implementation of the above approach:

C++




// CPP program for the above approach
#include <iostream>
#include <math.h>
using namespace std;
 
// Function to find politeness
int politeness(int n)
{
    int count = 0;
   
    // sqrt(2*n) as max length
    // will be when the sum starts
    // from 1
    // which follows the equation n^2 - n - (2*sum) = 0
    for (int i = 2; i <= sqrt(2 * n); i++) {
        int a;
        if ((2 * n) % i != 0)
            continue;
        a = 2 * n;
        a /= i;
        a -= (i - 1);
        if (a % 2 != 0)
            continue;
        a /= 2;
        if (a > 0) {
            count++;
        }
    }
    return count;
}
 
// Driver program to test above function
int main()
{
    int n = 90;
    cout << "Politeness of " << n << " = " << politeness(n)
         << "\n";
 
    n = 15;
    cout << "Politeness of " << n << " = " << politeness(n)
         << "\n";
    return 0;
}
 
// This code is contributed by Prajjwal Chittori


Java




// Java program for the above approach
import java.lang.Math;
public class Main {
   
  // Function to find politeness
  static int politeness(int n)
  {
    int count = 0;
 
    // sqrt(2*n) as max length
    // will be when the sum
    // starts from 1
    // which follows the
    // equation n^2 - n - (2*sum) = 0
    for (int i = 2; i <= Math.sqrt(2 * n); i++) {
      int a;
      if ((2 * n) % i != 0)
        continue;
      a = 2 * n;
      a /= i;
      a -= (i - 1);
      if (a % 2 != 0)
        continue;
      a /= 2;
      if (a > 0) {
        count++;
      }
    }
    return count;
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int n = 90;
    System.out.println("Politness of " + n + " = "
                       + politeness(n));
 
    n = 15;
    System.out.println("Politness of " + n + " = "
                       + politeness(n));
  }
}
 
// This code is contributed by Prajjwal Chittori


Python3




# python program for the above approach
import math
 
# Function to find politeness
def politeness(n):
    count = 0
     
    # sqrt(2*n) as max length will be
    # when the sum starts from 1
    # which follows the equation
    # n^2 - n - (2*sum) = 0
    for i in range(2, int(math.sqrt(2 * n)) + 1):
        if ((2 * n) % i != 0):
            continue
        a = 2 * n
        a = a // i
        a = a - (i - 1)
        if (a % 2 != 0):
            continue
        a //= 2
        if (a > 0):
            count = count + 1
    return count
 
 
# Driver program to test above function
n = 90
print ("Politeness of ", n, " = ", politeness(n))
n = 15
print ("Politeness of ", n, " = ", politeness(n))
 
# This code is contributed by Prajjwal Chittori


C#




// C# program for the above approach
using System;
public class GFG {
   
  // Function to find politeness
  static int politness(int n)
  {
    int count = 0;
 
    // sqrt(2*n) as max length
    // will be when the sum
    // starts from 1
    // which follows the
    // equation n^2 - n - (2*sum) = 0
    for (int i = 2; i <= Math.Sqrt(2 * n); i++) {
      int a;
      if ((2 * n) % i != 0)
        continue;
      a = 2 * n;
      a /= i;
      a -= (i - 1);
      if (a % 2 != 0)
        continue;
      a /= 2;
      if (a > 0) {
        count++;
      }
    }
    return count;
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int n = 90;
    Console.WriteLine("Politness of " + n + " = "
                       + politness(n));
 
    n = 15;
    Console.WriteLine("Politness of " + n + " = "
                       + politness(n));
  }
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
// JavaScript program for the above approach
 
  // Function to find politeness
 function politness(n)
  {
    let count = 0;
 
    // sqrt(2*n) as max length
    // will be when the sum
    // starts from 1
    // which follows the
    // equation n^2 - n - (2*sum) = 0
    for (let i = 2; i <= Math.sqrt(2 * n); i++) {
      let a;
      if ((2 * n) % i != 0)
        continue;
      a = 2 * n;
      a = Math.floor(a / i);
      a -= (i - 1);
      if (a % 2 != 0)
        continue;
      a = Math.floor(a / 2);
      if (a > 0) {
        count++;
      }
    }
    return count;
  }
 
// Driver Code
 
     let n = 90;
    document.write("Politness of " + n + " = "
                       + politness(n) + "<br/>");
 
    n = 15;
    document.write("Politness of " + n + " = "
                       + politness(n));
 
</script>


Output

Politeness of 90 = 5
Politeness of 15 = 3

 Time complexity:  O(sqrt(2*n)) ≈ O(sqrt(n))                                                                                                                     

 Auxiliary space: O(1)                                                                                                                                                      

This article is contributed by Shubham Bansal. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Example in c:

Approach:

Prompt the user to enter a number.
Read the number from the user and store it in a variable.
Initialize the politeness count to 0.
Initialize a variable to keep track of the running sum of consecutive numbers, starting from 1.
Initialize a variable to keep track of the starting number in the current consecutive sequence.
Loop through all numbers from 1 up to (num – 1).
Add the current number to the running sum.
If the running sum is greater than num, remove the starting number from the sum and increment the starting number until the sum is less than or equal to num.
If the running sum is equal to num, increment the politeness count.
Print the politeness count for the entered number.
End the program.

C++




#include <bits/stdc++.h>
using namespace std;
 
int main() {
    int num;
       cout<<"Enter a number: ";
      cin>>num;
     
    int politeness = 0;
    int sum = 0;
    int start = 1;
    for (int i = 1; i < num; i++) {
        sum += i;
        while (sum > num) {
            sum -= start;
            start++;
        }
        if (sum == num) {
            politeness++;
        }
    }
    cout<<"Politeness of "<<num<<": "<<politeness<<endl;
     
    return 0;
}


C




#include <stdio.h>
 
int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
     
    int politeness = 0;
    int sum = 0;
    int start = 1;
    for (int i = 1; i < num; i++) {
        sum += i;
        while (sum > num) {
            sum -= start;
            start++;
        }
        if (sum == num) {
            politeness++;
        }
    }
     
    printf("Politeness of %d: %d\n", num, politeness);
     
    return 0;
}


Java




import java.io.*;
 
public class GFG {
    public static void main(String[] args) {
        int num = 0;
        System.out.print("Enter a number: ");
 
        int politeness = 0;
        int sum = 0;
        int start = 1;
         
        for (int i = 1; i < num; i++) {
            sum += i;
             
            // Check if the sum is greater than the input number
            while (sum > num) {
                sum -= start;
                start++;
            }
             
            // If the sum equals the input number, increment politeness
            if (sum == num) {
                politeness++;
            }
        }
         
        System.out.println("Politeness of " + num + ": " + politeness);
    }
}


Python3




# Python code addition
 
num = input("Enter a number: ")
 
politeness = 0
sum = 0
start = 1
 
for i in range(1, num):
    sum += i
    while sum > num:
        sum -= start
        start += 1
    if sum == num:
        politeness += 1
 
print("Politeness of", num, ":", politeness)
 
# The code is contributed by Nidhi goel.


C#




using System;
 
class Program {
    static void Main() {
        int num;
        Console.Write("Enter a number: ");
        num = Convert.ToInt32(Console.ReadLine());
 
        int politeness = 0;
        int sum = 0;
        int start = 1;
        for (int i = 1; i < num; i++) {
            sum += i;
            while (sum > num) {
                sum -= start;
                start++;
            }
            if (sum == num) {
                politeness++;
            }
        }
        Console.WriteLine("Politeness of {0}: {1}", num, politeness);
    }
}


Javascript




let readlineSync = require('readline-sync');
 
let num = parseInt(readlineSync.question("Enter a number: "));
 
let politeness = 0;
let sum = 0;
let start = 1;
for (let i = 1; i < num; i++) {
    sum += i;
    while (sum > num) {
        sum -= start;
        start++;
    }
    if (sum == num) {
        politeness++;
    }
}
 
console.log("Politeness of " + num + ": " + politeness);


Output

Enter a number: Politeness of 0: 0

Time complexity: O(N^2), where N is the given number. This is because the program needs to iterate through all possible sequences of consecutive integers that sum to N.

Space complexity: O(1), because the program uses only a fixed amount of memory regardless of the size of the input number.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments