[Swift]浙大美女学霸征婚问题 随笔 第1张

问题1:求乘积为(7140229933)的两个质数?

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

Solution:

 1 import Foundation
 2 class Solution {
 3     func findBeauty(_ number:Int, _ target: Int) -> String {
 4         var primes = Set(2...number)
 5         //埃拉托色尼筛选法
 6         (2...Int(sqrt(Double(number)))).forEach {
 7             let _ = primes.subtract(stride(from: 2*$0, through: number, by: $0))
 8         }
 9         //转换为Double
10         let nums:[Double] = Array(primes).map{Double($0)}
11         var table:[Double:Double] = [Double:Double]()
12         for (firstIndex, num) in nums.enumerated() {
13             let res: Double = Double(target) / Double(num)
14             //可选链接
15             if table[res] == nil
16             {
17                 table[num] = Double(firstIndex)
18             }
19             else
20             {
21                 //转换为Int
22                 let res:Int = Int(res)
23                 let num:Int = Int(num)
24                 print(res)
25                 print(num)
26                 let str:String = res > num ? (String(num) + String(res)) : String(res) + String(num)
27                 return "Lin" + str
28             }
29         }
30         return String()
31     }
32 }

点击:Playground测试

1 //测试
2 print(Solution().findBeauty(100000, 7140229933))
3 //Print 85229
4 //Print 83777
5 //Print Lin8377785229

剧本的故事结局:

[Swift]浙大美女学霸征婚问题 随笔 第2张

[Swift]浙大美女学霸征婚问题 随笔 第3张

问题二:求乘积为(6541367***)的两个质数?

 1 import Foundation
 2 class Solution {
 3     func findBeauty2(_ number:Int, _ target: Int) -> [Int] {
 4         var primes = Set(2...number)
 5         //埃拉托色尼筛选法
 6         (2...Int(sqrt(Double(number)))).forEach {
 7             let _ = primes.subtract(stride(from: 2*$0, through: number, by: $0))
 8         }
 9         let nums:[Int] = Array(primes).sorted()
10         //最大值
11         let minNum:Int = target * 1000
12         //最小值
13         let maxNum:Int = minNum + 999
14         //遍历数组
15         for i in 0..<nums.count - 1
16         {
17             let num1:Int = getOdd(maxNum,nums[i])
18             let num2:Int = getOdd(minNum,nums[i])
19             let num3:Int = num1 * nums[i]
20             //质数必须是奇数
21             if num1 == num2 && nums.contains(num1) && minNum == (num3 - num3 % 1000)
22             {
23                print(num3)
24                return([nums[i],num1])
25             }
26         }
27         return [-1,-1]
28     }
29     
30     //质数必为奇数,获取奇数
31     func getOdd(_ num1:Int,_ num2:Int) -> Int
32     {
33         let number:Int = Int(ceil(Double(num1) / Double(num2)))
34         return number % 2 == 0 ? (number - 1) : number
35     }
36 }

点击:Playground测试

1 //测试
2 print(Solution().findBeauty2(100000, 6541367))
3 //Print 6541367489
4 //Print [67049, 97561]

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄