华为OD机试 2025A卷题库疯狂收录中,刷题点这里
专栏导读
本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。
一、题目描述
完全数(Perfect number),又称完美数或完备数,是一些特殊的自然数。
它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。
例如:28,它有约数1、2、4、7、14、28,除去它本身28外,其余5个数相加,1+2+4+7+14=28。
输入n,请输出n以内(含n)完全数的个数。
二、输入描述
输入一个数字n。
三、输出描述
输出不超过n的完全数的个数。
六、Python算法源码
import math
def get_perfect_num(i):
total = 1 # 1 is a factor of all numbers
for j in range(2, int(math.sqrt(i)) + 1):
if i % j == 0:
total += j
if j != i // j: # Avoid counting square roots twice
total += i // j
return total == i
def main():
n = int(input())
count = 0
for i in range(1, n + 1):
if get_perfect_num(i):
count += 1
print(count)
if __name__ == '__main__':
main()
七、JavaScript算法源码
function getPerfectNum(i) {
let sum = 1; // 1 is a factor of all numbers
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
sum += j;
if (j !== i / j) { // Avoid counting square roots twice
sum += i / j;
}
}
}
return sum === i;
}
function main() {
const n = parseInt(prompt('Enter n:'));
let count = 0;
for (let i = 1; i <= n; i++) {
if (getPerfectNum(i)) {
count++;
}
}
console.log(count);
}
main();
八、C算法源码
#include <stdio.h>
#include <math.h>
int getPerfectNum(int i) {
int sum = 1; // 1 is a factor of all numbers
for (int j = 2; j <= sqrt(i); j++) {
if (i % j == 0) {
sum += j;
if (j != i / j) { // Avoid counting square roots twice
sum += i / j;
}
}
}
return sum == i;
}
int main() {
int n;
scanf("%d", &n);
int count = 0;
for (int i = 1; i <= n; i++) {
if (getPerfectNum(i)) {
count++;
}
}
printf("%d\n", count);
return 0;
}
九、C++算法源码
#include <iostream>
#include <cmath>
using namespace std;
bool getPerfectNum(int i) {
int sum = 1; // 1 is a factor of all numbers
for (int j = 2; j <= sqrt(i); j++) {
if (i % j == 0) {
sum += j;
if (j != i / j) { // Avoid counting square roots twice
sum += i / j;
}
}
}
return sum == i;
}
int main() {
int n;
cin >> n;
int count = 0;
for (int i = 1; i <= n; i++) {
if (getPerfectNum(i)) {
count++;
}
}
cout << count << endl;
return 0;
}
🏆下一篇:华为OD机试真题 - 简易内存池(Python/JS/C/C++ 2025 A卷 200分)
🏆本文收录于,华为OD机试真题(Python/JS/C/C++)
刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。