getting prime factorial of an integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sheilani
    New Member
    • Sep 2013
    • 2

    getting prime factorial of an integer

    Can anyone please help me with the code of prime factorization. Example input:135
    The problem is I want to be an output of (3^3) (5^1) instead of 3,3,3,5.
    here's the code:
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <cmath>
    using namespace std;
    
    void get_divisors(int n);
    
    int main() 
    {
        int n = 0;
    
        cout << "Enter a number:";
        cin >> n;
        get_divisors(n);
        cout << endl; 
    }
    
    void get_divisors(int n)
     {
         int i;
         double sqrt_of_n = sqrt(n);
    
         for (i = 2; i <= sqrt_of_n; i++)
             if (n % i == 0) 
    		 {
                cout << i << ", "; 
                get_divisors(n / i);
                return; 
                     }
    
    
         cout << n;
     }
  • Nepomuk
    Recognized Expert Specialist
    • Aug 2007
    • 3111

    #2
    The reason you are only getting a list of factors is that you calculate one by one without remembering your last result. There are a few possible solutions to this but the one I'd suggest (as it needs the least changes in your code) is passing two further arguments to your get_divisors function: The last factor found and the number of times you've found it so far. Then do the output depending on those values.

    Comment

    • Sheilani
      New Member
      • Sep 2013
      • 2

      #3
      thank for your reply,but i dont know how to do it.

      Comment

      • Nepomuk
        Recognized Expert Specialist
        • Aug 2007
        • 3111

        #4
        OK, here are a few hints:
        • The signature of the changed function will be something like
          Code:
          void get_divisors(int n, int lastFactor, int power)
        • The initial call should be something like
          Code:
          get_divisors(n, 2, 0)
        • You can reduce the number of calls in your for-loop given the new parameters

        Comment

        Working...