Any faster way to find the number of “lucky triples”?

前端 未结 4 1203
盖世英雄少女心
盖世英雄少女心 2021-01-03 10:28

I am working on a code challenge problem -- \"find lucky triples\". \"Lucky triple\" is defined as \"In a list lst, for any combination of triple like (ls

4条回答
  •  一整个雨季
    2021-01-03 11:16

    Read up on the Sieve of Eratosthenes, a common technique for finding prime numbers, which could be adapted to find your 'lucky triples'. Essentially, you would need to iterate your list in increasing value order, and for each value, multiply it by an increasing factor until it is larger than the largest list element, and each time one of these multiples equals another value in the list, the multiple is divisible by the base number. If the list is sorted when given to you, then the i < j < k requirement would also be satisfied.

    e.g. Given the list [3, 4, 8, 15, 16, 20, 40]:

    Start at 3, which has multiples [6, 9, 12, 15, 18 ... 39] within the range of the list. Of those multiples, only 15 is contained in the list, so record under 15 that it has a factor 3.

    Proceed to 4, which has multiples [8, 12, 16, 20, 24, 28, 32, 36, 40]. Mark those as having a factor 4.

    Continue through the list. When you reach an element that has an existing known factor, then if you find any multiples of that number in the list, then you have a triple. In this case, for 16, this has a multiple 32 which is in the list. So now you know that 32 is divisible by 16, which is divisible by 4. Whereas for 15, that has no multiples in the list, so there is no value that can form a triplet with 3 and 15.

提交回复
热议问题