一个自然数问题,新手小白求解答
1. 编程输入一个自然数m,在1~m之间寻找因子个数最多的数。输入示范:
50
输出示范:
1-50之间,48的因子数为10,最多
#include <stdio.h> #include <stdlib.h> #include <math.h> //#define PRINTF 1 #define PRINTF 0 typedef struct result { int n; int count; } RESULT, *PRESULT; int _Factors(int n) { #if PRINTF == 1 printf("因子数:%d ", 1); #endif if (n == 1) { return 1; } int count = 2; int sqrt_n = (int)sqrt(n); for (int i = 2; i <= sqrt_n; i++) { if (n % i == 0) { #if PRINTF == 1 printf("%d ", i); #endif if(i == sqrt_n) { if (n / i == i) { count++; } else { count += 2; #if PRINTF == 1 printf("%d ", n / i); #endif } } else { count += 2; #if PRINTF == 1 printf("%d ", n / i); #endif } } } #if PRINTF == 1 printf("%d \n", n); #endif return count; } main() { int m; printf("输入一个正整数 m: "); scanf("%d", &m); printf("正整数 %d 的因子数个数为 %d\n", m, _Factors(m)); #if PRINTF == 0 int count; PRESULT p; p = (PRESULT)malloc(2*sizeof(RESULT)); p->n = 1; (p+1)->n = 1; (p+1)->count = 1; for (int i = 2; i <= m; i++) { count = _Factors(i); if (count > (p+1)->count) { p = (PRESULT)realloc(p, 2*sizeof(RESULT)); p->n = 1; (p+1)->n = i; (p+1)->count = count; } else if (count == (p+1)->count) { p->n += 1; p = (PRESULT)realloc(p, (p->n + 1)*sizeof(RESULT)); (p+p->n)->n = i; (p+p->n)->count = count; } } printf("1...%d 中因子数个数最多的为:\n", m); for (int i=1; i<=p->n; i++) { printf("%d 有%d个因子数\n", (p+i)->n, (p+i)->count); } free(p); #endif }
#include "stdio.h" #include <time.h> int yinshu(int n) { int i,j; for(i=1,j=0;i*i<n;i++)if(n%i==0)j++;; j*=2; //通常因数个数为偶数个 if(i*i==n)j++; //能正好开平方的因数数量为奇数个 return j; } void main() { int l,u,j,k,m,t; while(1) { scanf("%d%d",&l,&u); //输入数据范围,有一个数为0即退出死循环 if(!(l&&u))break; t=clock(); for(m=l,k=0;l<=u;l++) { j=0; //j=yinshu(l); if(l%2==0)j=yinshu(l); //只判断偶数,最多因数只存在于偶数 //printf("%3d,%3d----",l,j); if(j>k) { m=l; k=j; } } t=clock()-t; printf("max---%d,%d,用时%d毫秒\n",m,k,t); l=u=0; } }
[此贴子已经被作者于2016-6-5 08:12编辑过]