某企业招聘题目:获取最小的10000个素因子只有2、3、5的数

jthmath · · 3740 次点击
代码如下: ```go package suanfa import ( "fmt" "time" ) //获取前10000个素因子只有2 3 5的数 func Run() { var count int = 0 count++ var a [10002]uint64 = [10002]uint64{2, 3, 5} maxi := 2 //最大值的索引 var a2 uint64 var a3 uint64 var a5 uint64 p := time.Now() for i := 0; i < 9999; i++ { c := a[i] a2 = c * 2 if a[9999] != 0 && a2 >= a[9999] { break } a3 = c * 3 a5 = c * 5 maxi = sortInsert(&a, a2, a3, a5, i, maxi) //插入3个数 //fmt.Println(a[:maxi+1]) } q := time.Now() fmt.Println(q.Sub(p)) //fmt.Println(a[:maxi+1]) fmt.Println(a[9999]) } func sortInsert(a *[10002]uint64, a2 uint64, a3 uint64, a5 uint64, start int, maxi int) int { //fmt.Println(a2, a3, a5) //二分查找法查找 从后往前移动插入 //a5肯定在最后。 插入a2和a3 i2 := 0 i3 := 0 //插入 insert := 0 //搜索i2的位置 i := 0 j := start k := maxi for i = (start + maxi) / 2; j <= k; i = (j + k) / 2 { if a2 == a[i] { //找到了 i2 = i break } if a2 > a[i] { j = i + 1 } if a2 < a[i] { k = i - 1 } } //fmt.Println(i2) if i2 == 0 { //说明没找到啊 if a[i] < a2 { i2 = i + 1 } else { i2 = i } insert++ } //搜索i3的位置 j = i2 k = maxi for i = (j + k) / 2; j <= k; i = (j + k) / 2 { if a3 == a[i] { //找到了 i3 = i break } if a3 > a[i] { j = i + 1 } if a3 < a[i] { k = i - 1 } } //fmt.Println(i3) if i3 == 0 { //说明没找到啊 if a[i] < a3 { i3 = i + 1 } else { i3 = i } insert++ } //fmt.Println(i2, i3, insert, maxi) for i = maxi; i >= i3; i-- { if i+insert <= 9999 { a[i+insert] = a[i] //需要考虑i+insert > 10000的情况? } } maxi = maxi + insert if a[i3] != a3 { insert-- a[i3+insert] = a3 } //fmt.Println(a[:maxi+1]) if insert != 0 { for i := i3 - 1; i >= i2; i-- { a[i+1] = a[i] } a[i2] = a2 } //fmt.Println(a[:maxi+1]) maxi++ if maxi <= 9999 { a[maxi] = a5 //a5一定是最大值,追加在末尾 } else { maxi = 9999 } return maxi } ```
#38
更多评论
```python #! /usr/bin/env python def mul_nums(nums,size): curnums = [] retnums = [] minnum = nums[0] for c in nums: curnums.append(c) retnums.append(c) if c < minnum: minnum = c i = len(retnums) while i < size: minnum = curnums[0] minidx = 0 idx = 0 for c in curnums: if c < minnum: minnum = c minidx = idx idx += 1 minmulnum = curnums[0] * nums[0] for c in curnums: for d in nums: if (c * d) < minmulnum: minmulnum = (c * d) retnums.append(curnums[minidx]) curnums[minidx] = minmulnum i += 1 return retnums def main(): retnums = mul_nums([2,3,5],10000) for c in retnums: print('[%d]\n'%(c)) main() ```
#1
``` #!/usr/bin/env python # -*- coding:utf-8 -*- """ 10000以内 素因子只有2,3,5的数 只需要log2(10000) * log3(10000)*log5(10000)次循环 520次 最终的数据个数小于这个数 """ import math def findOnly235(): max = 10000 maxL2 = int(math.log(max, 2)) maxL3 = int(math.log(max, 3)) maxL5 = int(math.log(max, 5)) print maxL2, maxL3, maxL5 L = [] for i in range(maxL2): for j in range(maxL3): for k in range(maxL5): number = pow(2, i) * pow(3, j) * pow(5, k) if number <= max and number > 1: L.append(number) return L if __name__ == '__main__': l = findOnly235() l.sort() print l ```
#2