python - 将 C++ 转换为循环 python
问题描述
尝试搜索类似的问题,但无法解决此问题。不确定如何正确转换 C++ 循环中的某些功能。尤其是中的count < 20
条件main()
。
原始问题:https ://rosettacode.org/wiki/Anti-primes
#include <iostream>
int countDivisors(int n) {
if (n < 2) return 1;
int count = 2; // 1 and n
for (int i = 2; i <= n/2; ++i) {
if (n%i == 0) ++count;
}
return count;
}
int main() {
int maxDiv = 0, count = 0;
std::cout << "The first 20 anti-primes are:" << std::endl;
for (int n = 1; count < 20; ++n) {
int d = countDivisors(n);
if (d > maxDiv) {
std::cout << n << " ";
maxDiv = d;
count++;
}
}
std::cout << std::endl;
return 0;
}
我尝试的解决方案:
def countDivisors(n):
if (n < 2):
return 1
count = 2
for i in range(2, int(n/2)-1, 1):
print(i)
if(n%i == 0):
count = count + 1
return count
def main():
print("The first 20 anti-primes are: ")
n = 1
while count < 20:
d = countDivisors(n)
if(d > maxDiv):
print(n)
maxDiv = d
count += 1
n += 1
return 0
必填答案:
1 2 4 6 12 24 36 48 60 120 180 240 360 720 840 1260 1680 2520 5040 7560
解决方案
严格来说这两个for
循环:
for (int i = 2; i <= n/2; ++i)
会成为
for i in range(2,int(n/2)+1):
您的int(n/2)-1
代码中的 将i < n/2-1
在 C 中。
20个,
int maxDiv = 0, count = 0; // <-- ! for (int n = 1; count < 20; ++n) { int d = countDivisors(n); if (d > maxDiv) { std::cout << n << " "; maxDiv = d; count++; }
几乎就在那里,只是你没有在 PythonmaxDiv
中count
初始化。
maxDiv = 0 # <-- !
count = 0 # <-- !
n = 1
while count < 20:
d = countDivisors(n)
if(d > maxDiv):
print(n)
maxDiv = d
count += 1
n += 1
推荐阅读
- java - Android工作室创建新意图
- android - 如何在 Android 中的 TextInputLayout 上显示边框
- ios - 协议“App”只能用作通用约束,因为它具有 Self 或关联的类型要求
- ios - Swift:将 uid = uid 的 Firestore 子集合中的数据存储到对象中
- oracle - 如何使用 sysdba 连接到本地 oracle 数据库 19c
- html - 单击另一个按钮时如何关闭 HTML 中的按钮,以便折叠的文本不会重叠/按钮的数据
- c++ - “collect2.exe:错误:ld 返回 1 退出状态”是我在尝试使用 c lang 时得到的
- httpclient - 带有 Angular 元素的 SPFx Webpart 在 SharePoint 页面中不起作用
- java - 使用 Firestore 数据库检索和存储用户日期的 Java 算法
- python - 用于验证特殊字符和小写字母的 if 语句