Product of factors of number in C++


Given a number n we have to find its all factors and find the product of those factors and return the result, i.e, the product of factors of a number. Factors of a number are those numbers which can divide the number completely including 1. Like factors of 6 are − 1, 2, 3, 6.

Now according to the task we have to find the product all the factors of the number.

Input − n = 18

Output − 5832

Explanation − 1 * 2 * 3 * 6 * 9 * 18 = 5832

Input − n = 9

Output − 27

Explanation − 1 * 3 * 9 = 27

Approach used below is as follows to solve the problem −

  • Take the input num .

  • Loop from i = 1 till i*i<=num

  • Check if the num%i==0 then, check

    • If num%i == i then set the value of product = (product*i)%1e7

    • Else Set product as (product * i) % MAX and Set product as (product * num / i) % MAX.

  • Return the product.

Algorithm

Start
In Function long long productfactor(int num)
   Step 1→ Declare and Initialize product as 1
   Step 2→ For i = 1 and i * i <= num and i++
      If num % i == 0 then,
      If num / i == i then,
         Set product as (product * i) % MAX
      Else
         Set product as (product * i) % MAX
         Set product as (product * num / i) % MAX
   Step 3→ Return product
In Function int main()
   Step 1→ Declare and initialize n as 9
   Step 2→ Print the result productfactor(n)
Stop

Example

 Live Demo

#include <stdio.h>
#define MAX 1000000000
// find the product of the factors
long long productfactor(int num){
   long long product = 1;
   for (int i = 1; i * i <= num; i++){
      if (num % i == 0){
         //equal factors should be multiplied only once
         if (num / i == i)
         product = (product * i) % MAX;
         // Else multiply both
         else {
            product = (product * i) % MAX;
            product = (product * num / i) % MAX;
         }
      }
   }
   return product;
}
int main(){
   int n = 9;
   printf("%lld\n", productfactor(n));
   return 0;
}

Output

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

27

Updated on: 13-Aug-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements