PROBLEM STATEMENT :
Find maximum difference between the prime numbers in the given range. [L,R]
SOME CONDITION EXAMPLE :
Range: [ 1, 10 ] The maximum difference between the prime numbers in the given range is 5.
Difference = 7 - 2 = 5
Range: [ 5, 5 ] There is only one distinct prime number so the maximum difference would be 0.
Range: [ 8 , 10 ] There is no prime number in the given range so the output for the given range would be -1.
Range: [ 2 - 7 ] . This should return 5. [ 7 - 2 ] = 5
R Code :
The below R code works fine in R studio for all input I have passed. But when I ran the similar code in hackerEarth Env. Getting Errors
Input :
5
5 5
2 7
8 10
10 20
4 5
input <- readLines(stdin(), n=6)
total <- as.numeric(input[1])
val <- 1:total
for (i in 1:total )
{
val[i] <- input[i+1]
}
df <- data.frame(val)
df <- str_split_fixed(df$val, " ", 2)
lf <- data.frame(l=df[,1],r=df[,2])
dat <- as.data.frame(sapply(lf, as.numeric))
#Find Prime Sequence
sieve <- function(n)
{
n <- as.integer(n)
if(n > 1e6) stop("n too large")
primes <- rep(TRUE, n)
primes[1] <- FALSE
last.prime <- 2L
for(i in last.prime:floor(sqrt(n)))
{
primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE
last.prime <- last.prime + min(which(primes[(last.prime+1):n]))
}
which(primes)
}
#Find Next Prime
np <- function(x){
if (x==1L | x==2L) {return(2L)}
else {
temp <- x+1
test <- 2:x
while( any( (temp %% test) == 0 ) ){
temp <- temp+1
}
temp
} }
# Pass LR
prime <- function(l,r)
{
if (l==r) { return(0L) }
else if( (r - np(l)) == 0 ) { return(0L) }
else if( max(sieve(r)) - np(l) < 0) { return(-1L) }
else { return(max(sieve(r)) - np(l)) }
}
cat(mapply(prime,dat$l,dat$r),sep='\n')
R studio Output :
0
5
-1
8
0
Hacker Earth Output :
Getting below two Errors
Error in seq.int(2L * last.prime, n, last.prime) : wrong sign in 'by' argument Calls: mapply -> -> sieve In addition: Warning message: In if (is.character(fun)) fun <- get(fun, mode = "function", envir = parent.frame()) : closing unused connection 3 (stdin) Execution halted
Time Limit Exceeded
Is there a better way to achieve the desired results in less than a second. Corrections/Suggestions are highly appreciated