Christmas Bunny
Christmas Bunny

Reputation: 145

Project Euler 3 Solution

In the following snippet from https://github.com/nayuki/Project-Euler-solutions/blob/master/p003.java :

private static long smallestFactor(long n) {    
  for (long i = 2, end = Library.sqrt(n); i <= end; i++) {    
    if (n % i == 0)    
      return i;   
  }    
  return n; // Prime    
}

I was a bit confused with the return n part. Is n going to assume the value of i after it's returned in the if statement? Why?

Upvotes: 0

Views: 243

Answers (2)

Mohit Aphale
Mohit Aphale

Reputation: 51

lets take a num.

num is divisible upto its half (i.e factors)

Implement Sieve of Eratosthenes for finding prime_numbers. It's an efficient process for finding Prime numbers. And then check whether the returned primes divide the "num" or not...

Upvotes: 0

EvilTeach
EvilTeach

Reputation: 28837

No. It returns the unchanged parameter to indicate that it is prime.

If it is not prime, it returns the factor that shows it is not prime.

Upvotes: 2

Related Questions