The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Running time: 2ms
Assessment: This was when I switched from C++ to Java, and this solution is a lot better than my C++ solution. This one finishes, and finishes pretty quickly.
public class Problem003b { public static void main(String[] args) { long begin = System.currentTimeMillis(); long n=600851475143L; for (long i = 2; i <= n; i++) { if (n % i==0) { System.out.println(i); n = n / i; i = 2; } } long end = System.currentTimeMillis(); System.out.println(end-begin + "ms"); } }
Read the question first man then post the solutions. this is worst solution I ever seen in my life of any problem
Cool story bro.
This works perfectly except I think you have an error in your condition in the for loop. It should be for(long i = 2; i < n; i++), otherwise you'd end up with n=1.
This is one of the worst solutions and in a case if you’re giving such a solution in a job interview, then it might affect adversely the chances of getting selected.
A much better solution would be some thing like this:
#include
#include
void main()
{
long int inputnum=600851475143;
int primefactor=0;
while(inputnum%2==0)
{
inputnum=inputnum/2;
primefactor=2;
}
for(int i=3;i<=inputnum;i++)
{
while(inputnum%i==0)
{
inputnum=inputnum/i;
primefactor=i;
}
}
cout<<primefactor
}
//
//after the cout
cout<<primefactor;
return;
}
#include
#include
using namespace std;
int main()
{
long int inputnum=600851475143;
int primefactor=0;
while(inputnum%2==0)
{
inputnum=inputnum/2;
primefactor=2;
}
for(int i=3;i<=inputnum;i++)
{
while(inputnum%i==0)
{
inputnum=inputnum/i;
primefactor=i;
}
}
cout<<primefactor;
return 0;
}