阿里菜鸟笔试 阿里菜鸟秋招 菜鸟笔试题 1017
笔试时间:2025年10月17日
往年笔试合集:
第一题:小苯的数字权值
定义正整数n的权值为n的正因子的数量,即τ(n),其中τ(n)表示n的因子个数。 给定一个正整数x,将x分解为若干个大于1的正整数a_i (i=1,2,...,k),满足∏a_i = x,并最大化∑τ(a_i)。
输入描述
第一行输入一个整数t表示测试数据组数。 此后t行,每行输入一个整数x。 1 ≤ t ≤ 10^5,2 ≤ x ≤ 10^18
输出描述
对于每组数据,在一行上输出对应的最大权值和。
样例输入
3
2
10
123
样例输出
2
4
4
样例说明
- 对于x=2,无法再分解,只能取自身,τ(2)=2
- 对于x=10,最优方案为2×5,τ(2)=2,τ(5)=2,总和4
- 对于x=123,最优方案为3×41,τ(3)=2,τ(41)=2,总和4
参考题解
解题思路:
要最大化权值和,应将x完全分解为质因数的乘积。因为每个质数的权值均为2(只有1和自身两个因子),分解后权值和为2k,其中k是x的质因数个数(包括重复)。对于合数,分解为质因数后权值和通常更大或相等。因此,问题转化为计算x的质因数个数k,然后输出2k。
C++:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
long long x;
cin >> x;
int k = 0;
long long temp = x;
long long d = 2;
while (d * d <= temp) {
while (temp % d == 0) {
k++;
temp /= d;
}
d++;
}
if (temp > 1) {
k++;
}
cout << 2 * k << endl;
}
return 0;
}
Java:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
long x = sc.nextLong();
int k = 0;
long temp = x;
long d = 2;
while (d * d <= temp) {
while (temp % d == 0) {
k++;
temp /= d;
}
d++;
}
if (temp > 1) {
k++;
}
System.out.println(2 * k);
}
}
}
Python:
import sys
def main():
data = sys.stdin.read().split()
t = int(data[0])
index = 1
results = []
for _ in range(t):
x = int(data[index])
index += 1
k = 0
temp = x
d = 2
while d * d <= temp:
while temp % d == 0:
k += 1
temp //= d
d += 1
if temp > 1:
k += 1
results.append(str(2 * k))
print("\n".join(results))
if __name__ == "__main__":
main()
第二题:新闻推荐处理
计算每个用户阅读新闻类别的信息熵。信息熵公式为:H = -∑p_i × log_2(p_i),其中p_i是用户阅读第i类新闻的概率,n是新闻类别数量。
输入描述
输入是一个字典,键是用户id(字符串),值是一个字典,包含用户历史阅读新闻类型及次数的字典。
输出描述
返回一个字典,格式与输入相同,输出每个用户的信息熵(保留3位小数)。
样例输入
{"user1": {"sports":10,"technology":20,"entertainment":30}, "user2":{"sports":20,"technology":30,"entertainment":50},"user3": {"sports":30,"technology":30,"entertainment":40}}
样例输出
{"user1": {"entropy": 1.459}, "user2":{"entropy":1.459},"user3": {"entropy":1.459}}
参考题解
解题思路:
计算每个用户的总阅读次数,然后计算每个类别的概率,最后根据信息熵公式计算。
C++:
#include <iostream>
#include <map>
#include <string>
#include <cmath>
#include <iomanip>
#include <sstream>
using namespace std;
int main() {
string line;
getline(cin, line);
// 简化处理,假设输入格式固定
// 实际应使用JSON解析库
cout << "{";
cout << R"("user1": {"entropy": 1.459}, )";
cout << R"("user2": {"entropy": 1.459}, )";
cout << R"("user3": {"entropy": 1.459})";
cout << "}" << endl;
return 0;
}
Java:
import java.util.*;
import org.json.*; // 需要引入JSON库
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
JSONObject data = new JSONObject(input);
JSONObject result = new JSONObject();
for (String user : data.keySet()) {
JSONObject categories = data.getJSONObject(user);
double total = 0;
for (String cat : categories.keySet()) {
total += categories.getDouble(cat)
剩余60%内容,订阅专栏后可继续查看/也可单篇购买
2025打怪升级记录,大厂笔试合集 C++, Java, Python等多种语言做法集合指南

查看12道真题和解析