<LeetCode><Easy>263 Ugly Number (因式分解)

来源:互联网 发布:淘宝神笔模板编辑 编辑:程序博客网 时间:2024/05/29 19:49

Write a program to check whether a given number is an ugly number.

Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.

Note that 1 is typically treated as an ugly number.

#Python2     TimeOut

class Solution(object):    def isUgly(self, num):        """        :type num: int        :rtype: bool        """        if num==1:            return False        factors=lambda num:[i for i in xrange(2,abs(num)+1) if not num%i]        pFactors=[factors(i)[0] for i in factors(num) if len(factors(i))==1]        for p in pFactors:            if p not in [2,3,5]:                return False        return True

#python2 TimeOut

class Solution(object):    def isUgly(self, num):        """        :type num: int        :rtype: bool        """        if num<2:            return False        factors=lambda num:[i for i in xrange(2,num+1) if not num%i]        i=1        while i <num:            i+=1            if not num%i:                if len(factors(i))==1:                    if i not in [2,3,5]:                        return False        return True

#Python2 56ms

class Solution(object):    def isUgly(self, num):        """        :type num: int        :rtype: bool        """        if num<1:            return False        def lower(n,p=2):            while 1:                if n%p:                    return n                else:                    n/=p        return not lower(lower(lower(num),3),5)-1



0 0
原创粉丝点击