c - 打印出特定间隔之间的完美数字
问题描述
// starting, end, number, sum of the divisor, delimiter
int pocetok, kraj, broj, zbir_na_deliteli=0, delitel=1;
printf("Vnesi go intervalot: "); // Enter the interval
scanf("%d%d", &pocetok, &kraj);
for(broj=pocetok;broj<=kraj;broj++)
for(;delitel<broj;delitel++){
if(broj%delitel==0)
zbir_na_deliteli+=delitel;
}
if(zbir_na_deliteli==broj)
// The number %d is a perfect number
printf("Brojot %d e sovrshen broj\n", broj);
}
这是我写的程序。我实际上是在逐行将它与一个已解决的程序进行比较,该程序执行完全相同的操作,除了一个有效但这个无效。
有人可以向我解释我做错了什么吗?
解决方案
有人可以向我解释我做错了什么吗?
计数器delitel
需要在每个循环的 1 处重新启动
// for(;delitel<broj;delitel++){
for (int delitel = 1; delitel < broj; delitel++) {
每次循环总和zbir_na_deliteli
需要重置为 0
for (int broj = pocetok; broj <= kraj; broj++) {
int zbir_na_deliteli = 0;
示例代码:
void Printing_out_the_perfect_numbers(int pocetok, int kraj) {
for (int broj = pocetok; broj <= kraj; broj++) {
int zbir_na_deliteli = 0;
for (int delitel = 1; delitel < broj; delitel++) {
if (broj % delitel == 0) {
zbir_na_deliteli += delitel;
}
}
if (zbir_na_deliteli == broj) {
printf("Brojot %d e sovrshen broj\n", broj);
}
}
}
int main() {
Printing_out_the_perfect_numbers(1, 10000);
}
输出
Brojot 6 e sovrshen broj
Brojot 28 e sovrshen broj
Brojot 496 e sovrshen broj
Brojot 8128 e sovrshen broj
更快的方法不会测试除法broj
,而是测试 的平方根broj
。与其直接计算平方根,不如跟踪商和余数。许多编译器会为商和余数(%
和/
)提供一次计算,以免产生额外昂贵的除法。
void Printing_out_the_perfect_numbers(int pocetok, int kraj) {
for (int broj = pocetok; broj <= kraj; broj++) {
int zbir_na_deliteli = 0;
int kvocient = broj;
for (int delitel = 1; delitel < kvocient; delitel++) {
if (broj % delitel == 0) {
kvocient = broj / delitel;
zbir_na_deliteli += delitel;
if (kvocient > delitel) {
if (delitel != 1) zbir_na_deliteli += kvocient;
} else {
break;
}
}
}
if (zbir_na_deliteli == broj) {
printf("Brojot %d e sovrshen broj\n", broj);
}
}
}
推荐阅读
- c# - VerifyCommitted - 插件上的事务尚未提交错误
- java - Maven安装中的编译错误:错误:包org.springframework.stereotype不存在
- python - CSV NamedTemporaryFile 未正确保存
- css - 如何在 Django 静态文件中使用 background-image css 属性
- ruby-on-rails - 在 Ruby on Rails 中使用 Ajax 更改本地 Ruby 变量
- python - Python 字典:使 key:value 成为键并附加新值
- javascript - setTimeout() 立即执行函数,没有延迟
- python - Seaborn 热图未显示从字符串转换为数字的列
- scala - 在 Slick 和 Scala 中使用带参数的过滤函数进行柯里化?
- ruby-on-rails - 仅在生产中需要 mysql2 时,为什么会出现此错误?