现在的位置: 首页 > 综合 > 正文

查找1到1000的完数

2013年01月25日 ⁄ 综合 ⁄ 共 722字 ⁄ 字号 评论关闭

名词解释:

完数(Perfect number),又称完美数或完备数,是一些特殊的自然数。它所有的真因子(即除了自身以外的约数)的和(即因子函数),恰好等于它本身。

公式2p−1(2p−1) (p是指素数)。

由公式还可知有趣的二进制的格式表示,为p个1及p-1个0组成。

610 = 1102
2810 = 111002
49610 = 1111100002
812810 = 11111110000002

#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main (int argc,char *argv[])
{
  int m, i, s;
  int buffersize=1000;
  char *head,*point, *buffer = malloc(buffersize);
  char tmp[10];
  point = buffer;
  for (m = 1; m <= 1000; m++)
    {
      s = 0;
        head=point;
#define __MYPRINTF(format,...)\
        memset(tmp,'\0',sizeof(tmp));\
      snprintf (tmp,sizeof(tmp),format, ## __VA_ARGS__);\
        memcpy(point,tmp,strlen(tmp));\
        point += strlen(tmp);
        __MYPRINTF("%d:",m);
      for (i = 1; i < m; i++)
        {
        if (m % i == 0)
          {
            s = s + i;
            __MYPRINTF ("%d,", i);
          }
        }
      if (s == m)
        {
          __MYPRINTF ("\n");
        }
      else
        {
          point = head;
        }
        *point = '\0';
    }
        printf("%s",buffer);
        return 0;
}

抱歉!评论已关闭.