关于求因数的题目
一个数如果恰好等于它的因子之和,这个数就称为完数。例如:6=1+2+3。求出1000内的完数输出格式为:6 its factors are 1, 2, 3 本帖最后由 tommyyu 于 2022-10-4 17:09 编辑
#include<iostream>
using namespace std;
int main()
{
int factors;
for(int i=2; i<=1000; ++i) {
int sum = 0;
int count = 0;
for(int j = 1; j < i; ++j) {
if(i%j == 0) {
factors = j;
sum += j;
}
}
if(sum == i) {
cout<<i<<" its factors are ";
for(int j=0; j<count-1; ++j) cout<<factors<<",";
cout<<factors<<endl;
}
}
return 0;
}
输出:6 its factors are 1,2,3
28 its factors are 1,2,4,7,14
496 its factors are 1,2,4,8,16,31,62,124,248 tommyyu 发表于 2022-10-4 16:56
输出:
看好,这是c语言板块{:10_260:} 青出于蓝 发表于 2022-10-4 16:58
看好,这是c语言板块
{:10_282:}没有仔细看
现在已经改成C++了 #include <stdio.h>
void foo(int n)
{
int b , c , d , i ;
for(c = 0 , i = 1 ; i < n ; i ++) if(! (n % i)) d = i ;
for(i = 0 , b = 0 ; i < c ; i ++) b += d ;
if(b == n) {
printf("%3d its factors are : %d" , n , d) ;
for(i = 1 ; i < c ; i ++) printf(",%d" , d) ;
printf("\n") ;
}
}
int main(void)
{
int i ;
for(i = 2 ; i <= 1000 ; i ++) foo(i) ;
}
编译、运行实况:
D:\\C>g++ -o x x.c
D:\\C>x
6 its factors are : 1,2,3
28 its factors are : 1,2,4,7,14
496 its factors are : 1,2,4,8,16,31,62,124,248
D:\\C> #include <stdio.h>
bool wanshu(int n) { //传说中的完数
int sum = 0; //因子和
for (int i = 1; i < n; ++i) //1枚举到n - 1
if (n % i == 0) //如果i是n的因数
sum += i; //加入和
return n == sum; //判断一下
}
int main() {
for (int i = 1; i <= 1000; ++i) {
if (wanshu(i)) //是完数输出
printf("%d ", i);
}
} tommyyu 发表于 2022-10-4 17:09
没有仔细看
现在已经改成C++了
哈哈哈哈,谢谢大佬!!
页:
[1]