求一个hash函数:输入n个非负整数k_1、k_2、...、k_n,随机输出集合{0、1、2、...、m}中的一个非负整数。要求n可配置、m可配置,随机性尽量高、复杂度尽量低,C语言版,C++版,java版,python版本,各来一个
时间: 2023-07-10 10:11:33 浏览: 39
C语言版:
```c
#include <stdint.h>
uint64_t hash_func(uint64_t* nums, uint64_t n, uint64_t m) {
uint64_t result = 0;
for (uint64_t i = 0; i < n; i++) {
result = (result + nums[i]) % m;
}
return result;
}
```
C++版:
```c++
#include <vector>
#include <cstdint>
uint64_t hash_func(std::vector<uint64_t>& nums, uint64_t m) {
uint64_t result = 0;
for (auto num : nums) {
result = (result + num) % m;
}
return result;
}
```
Java版:
```java
import java.util.List;
public class HashFunc {
public static long hashFunc(List<Long> nums, long m) {
long result = 0;
for (Long num : nums) {
result = (result + num) % m;
}
return result;
}
}
```
Python版:
```python
def hash_func(nums, m):
result = 0
for num in nums:
result = (result + num) % m
return result
```
以上代码都是使用取模的方式实现hash函数,复杂度为O(n),随机性较高,可以满足要求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)