python求因子个数_python求约数的个数

题目:输入n个整数,依次输出每个数的约数的个数(运行时间1500ms)

ContractedBlock.gif

ExpandedBlockStart.gif

importosdefcount(x):

factor= 2num= 1

while (factor * factor <=x):

count= 1

while (x % factor ==0):

count+= 1x/=factor

num*=count

factor+= 1

return (num * (1 + (x > 1)))try:

n= int(input()) #行数

if(n!=0):#if(n>0 and n<=1000):

s =list(map(int, input().split()))#print(s)

else:

os._exit(0)for item ins:

it=count(item)print(it)except:pass

View Code

python计算约数个数的方法:

从1到n枚举,判断是否可以整除 时间复杂度O(n)

defcountDivisors(num):return sum(num % i == 0 for i in range(1, num + 1))

从1到sqrt(n)枚举,判断是否可以整除

defcountDivisors(num):

cnt=0

sqrt= int(num ** 0.5)for x in range(1, sqrt + 1):if num % x ==0:

cnt+= 1

return cnt * 2 - (sqrt ** 2 == num)

分解质因子,求幂的乘积

defcountDivisors(num):

ans= 1x= 2

while x * x <=num:

cnt= 1

while num % x ==0:

cnt+= 1num/=x

ans*=cnt

x+= 1

return ans * (1 + (num > 1))

李旭的java代码(运行时间200ms)为什么这个这么快呢

ContractedBlock.gif

ExpandedBlockStart.gif

public classyue {public static voidmain(String[] args) {

System.out.println("N:");

Scanner sc= newScanner(System.in);int n =sc.nextInt();int []a=new int[n];for (int i=0;i

a[i]=sc.nextInt();

}for(int i=0;i

num++;

}else if(a[i]%j==0){

num+=2;

}

}

System.out.println(num);

}

}

}

View Code

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值