Tuesday 30 September 2014

HACKERRANK.COM => PROJECTEULER SOLUTION # 3



This problem is a programming version of Problem 3 from projecteuler.net
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of a given number N?
Input Format
First line contains T, the number of test cases. This is followed by T lines each containing an integer N.
Output Format
For each test case, display the largest prime factor of N.
Constraints
1≤T≤10
10≤N≤1012
Sample Input
2
10
17
Sample Output
5
17


First of all I submitted this code and this code showed Time limit exceeded in test case 5.
So this is not the most efficient code to find the largest prime factor of a given number.

/*****************************************************/

#include<stdio.h>

int isPrime(long long int n)
{
    long long int i;
    for(i=2;i*i<=n;i++)
        if(n%i==0)
            return 0;
    return 1;
}

long long int findLargestPrimeFactor(long long int n)
{
    long long int counter=3;
    while(n%2==0)
        n/=2;
    if(n==1)
        return 2;
    while(n!=1)
    {
        if(isPrime(n))
            return n;
        while(n%counter==0)
            n/=counter;
        counter+=2;
   }
   return counter-2;
}

int main()
{
    int t;
    long long int n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%lld",&n);
        printf("%lld\n",findLargestPrimeFactor(n));
    }
    return 0;
}
/*****************************************************/

No comments:

Post a Comment