Lazy Evaluation

Sort by

recency

|

54 Discussions

|

  • + 0 comments

    The key take of Test case 3 is the order of checking if prime and palindrome.

    prime?(x) && palindrome?(x) # does not pass
    palindrome?(x) && prime?(x) # pass
    

    It's quite clever to check the less complex operation first

  • + 0 comments

    **BY USING THIS CODE WE SOLVE THE ABOVE PROBLEM BUT THE THIRD CASE IS NOT COMPLETE ** def prime?(number) return ary = (2..number-1).collect{|i| i if number%i==0}.compact.length==0 end def palidrom?(num) i = 0 num = num.to_s j = num.length-1 while i<=j if(num[i]!=num[j]) return false end i+=1 j-=1 end return true end arr = [] num = gets.chomp.to_i i = 0 number = 2 while(i!=num)

    if(palidrom?(number) && prime?(number))
    i+=1
    arr.push(number)
    end
    number+=1
    

    end print arr

  • + 0 comments

    More elegant solution:

    def prime?(x)
        return false if x < 2
        
        checker = Math.sqrt(x).to_i # 4
        2.upto(checker).each {|i| return false if x % i == 0 }
        
        true
    end
    
    palindrom_array = -> (array_size) do
        2.upto(Float::INFINITY).lazy.select do |x| 
            prime?(x) && x.digits.join.to_i == x
        end.first(array_size.to_i)
    end
    
    N = gets
    print palindrom_array.(N)
    
  • + 0 comments
    require 'prime'
    n = gets.to_i
    palindromic_primes = Prime.lazy.select { |num| num.to_s == num.to_s.reverse }.take(n)
    puts palindromic_primes.to_a.inspect
    
  • + 0 comments

    Here is Lazy evaluation problem solution - https://www.gyangav.com/2022/10/hackerrank-lazy-evaluation-problem-solution.html