Project Euler #234: Semidivisible numbers

  • + 1 comment
    # Enter your code here. Read input from STDIN. Print output to STDOUT
    import math as m
    import sys
    
    def lps(n):
        ref=m.floor(m.sqrt(n))
        result=1
        temp=[]
    
        for i in range(2,ref+1):
            #lets find out the greatest prime no less than ref
            
            for j in range(2,i):
                if i%j==0:
                    break
            else:#this else is for FOR loop
                temp.append(i)
                #print("lps appended",temp)
        result=max(temp)
        return result # returns lps value for input as n
    
    def ups(n):
        ref=m.ceil(m.sqrt(n))
        result=1
        temp=[]
    
        for i in range(ref,30):
            #lets find out the smallest prime no greater than ref
            for j in range(2,i):
                if i%j==0:
                    break
            else:
                temp.append(i)
                #print("ups appended",temp)
        result=min(temp)
        return result
    
    #main function:
    arr=list(map(int,input().split()))
    L=arr[0]
    R=arr[1]
    if (L not in range(4,pow(10,18))) or (R not in range(4,pow(10,18)))or((R-L)>pow(10,16)):
        sys.exit()
    
    ans_lst=[]
    try:
        for i in range(L,R+1):
            lps_val=lps(i)
            #print("debug lps val=",lps_val)
            ups_val=ups(i)
            #print("debug ups val=",ups_val)
            if (i%lps_val==0 and i%ups_val!=0) or (i%ups_val==0 and i%lps_val!=0):
                ans_lst.append(i)
        print(sum(ans_lst)%1004535809)
        #print("debug ans_list : ",ans_lst)
    except ZeroDivisionError:
        print("Unexpected glitch")
        sys.exit()