< Back to forum

Magic Card


#include <iostream>

using namespace std;
long fact(int n)
{
    if(n==1 || n==0)
        return 1;
    else
        return n*fact(n-1);
}

int main() {
    int t,n;
    cin>>t;
    while(t--)
    {
        cin>>n;
        int c=0,m,d=0,k=2,h=1;
        m=n;
        for(int i=2;i<=n;++i)
        {
            
            
            
            if(m%i==0)
            {
                if(k==i)
            {
                d++;
            }
                c++;
                m/=i;
                i=i-1; 
                }
            
            else
            {if(d>1)
             h=h*fact(d);
             
                d=0;
                k++;
                    if(m==1)
            {
            break;
            }
        }      
        }

        cout<<(fact(c))/h<<endl;
    }
    return 0;
}

 

 

 

 

This is my code. Its keeps saying time out 1s. How can i overcome this timeout issue.

Asked by: Nitesh_Prasad on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.


Enter your answer details below:


Enter your comment details below:




1 Answer(s)

avatar

Your loop for finding prime factors is running 'n' times every time. You can optimise this loop to 'sqrt(n)' for finding factors. Then you will not be getting tle.

Shivansh_Agarwal last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.