Algorithm to determine if array contains n…n+m?

前端 未结 30 3105
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 02:06

    Product of m consecutive numbers is divisible by m! [ m factorial ]


    so in one pass you can compute the product of the m numbers, also compute m! and see if the product modulo m ! is zero at the end of the pass

    I might be missing something but this is what comes to my mind ...

    something like this in python

    my_list1 = [9,5,8,7,6]

    my_list2 = [3,5,4,7]

    def consecutive(my_list):

    count = 0
    prod = fact = 1
    for num in my_list:
        prod *= num
        count +=1 
        fact *= count
    if not prod % fact: 
        return 1   
    else:   
        return 0 
    

    print consecutive(my_list1)

    print consecutive(my_list2)


    HotPotato ~$ python m_consecutive.py

    1

    0

提交回复
热议问题