因数分解

    最近有同事面试,面试官出了一现场编程题:给定一个正整数,输出它所包含的因数,如输入6,输出:1 2 3;输入7,输出1 7;输入8,输出 1 2 2 2。

回来自己编程并实验了一下:

(1)非递归实现

void factorization_01(unsigned int n)
{
  unsigned int i, x = n;
  unsigned int counter = 0; // record the time of for loop
  printf("%10d: 1 ",n);
  for(i =2; (i <= n) && (x != 1); i ++)
  {
    counter ++;
    if(x % i == 0)
    {
      printf("%d ",i); 
      x = x / i; 
      i--;
    }
  }
  printf("---counter = %d--by factorization_01\n", counter);
}
(2)递归实现

void factorization_02(unsigned int n, unsigned int k)
{
  static unsigned int counter = 0; // record the times that factorization_02 is called  
  if(counter == 0)
  {
    printf("%10d: 1 ", n);
  }
  counter ++;
  if(n == 1) 
  {
    printf("---counter = %d--by factorization_02\n", counter); 
    counter = 0;
    return;
  } 
  if(n % k == 0)
  {
     printf("%d ",k);
     factorization_02(n/k, k);
  }
  else
  {
     factorization_02(n, k+1);
  }
}
测试输出结果如下:

      8575: 1 5 5 7 7 7 ---counter = 10--by factorization_01
      8575: 1 5 5 7 7 7 ---counter = 11--by factorization_02
        17: 1 17 ---counter = 16--by factorization_01
        17: 1 17 ---counter = 17--by factorization_02
       258: 1 2 3 43 ---counter = 44--by factorization_01
       258: 1 2 3 43 ---counter = 45--by factorization_02
    441000: 1 2 2 2 3 3 5 5 5 7 7 ---counter = 15--by factorization_01
    441000: 1 2 2 2 3 3 5 5 5 7 7 ---counter = 16--by factorization_02
         1: 1 ---counter = 0--by factorization_01
         1: 1 ---counter = 1--by factorization_02
         2: 1 2 ---counter = 1--by factorization_01
         2: 1 2 ---counter = 2--by factorization_02


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值