Euler Problem 3 – Largest Prime Factor

Largest Prime Factor

Problem 3

The prime factors of 13195 are 5, 7, 13 and 29. 

What is the largest prime factor of the number 600851475143 ?

Had lots of problem solving this one. Here are few of them. Just in case if you face the same, you can resolve it

  1. Error in seq.default(3, floor(num/2), by = 2) :  wrong sign in ‘by’ argument

If the num passed was 3 then floor(num/2) would give 1 and then creating a sequence from 3 to 1 with by = +2 is impossible . Hence the error. Resolved it by handling the integers 3 and 5 separately.

  1. Error in seq.default(3, floor(num/2), by = 2) :  ‘by’ argument is much too small

Now the code worked well for num = 13195 which was shared as an example. As I entered the given number i.e 600851475143 it gave the above error.

  Researching further I got to know that R can hold max integer value till 2147483647 and out number is way bigger than this. To find the max integer number r can hold try .Machine$integer.max in R console.

Largest_prime_factor <- function(num) {
 for (i in seq(3, floor(sqrt(num)), by=2)) {
   if (num %% i == 0 & is_prime(i)) {
     maxNumber = i      
   }
 }
 return(maxNumber)
}


is_prime <- function(num) {
 flag = 0
 if (num %% 2 == 0) return(FALSE)
 if (num == 3 | num == 5) return(TRUE)
 for (i in seq(3, floor(num/2), by=2)) {
   if (num %% i == 0) {
     flag = 1
     return(FALSE)
   }
}
 return(TRUE)
} 
Advertisements

3 thoughts on “Euler Problem 3 – Largest Prime Factor

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s