整数分解,称质因子分解。在数学中,整数分解问题是指:给出一个正整数,将其写成几个素数的乘积的形式。

(每个合数都可以写成几个质数相乘的形式,这几个质数就都叫做这个合数的质因数)

1.试除法(适用于范围比较小)

   无论素数判定还是因子分解,试除法(Trial Division)都是首先要进行的步骤。令m=n,从2~根n一一枚举,如果当前数能够整除m,那么当前数就是n的素数因子,并用整数m

将当前数除尽为止。

  若循环结束后m是大于1的整数,那么此时m也是n的素数因子。

事例如HDU1164:15mm

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#define N 65535
using namespace std;
int factor[N],top;
void divide(int n)
{
    for(int i=2; i<=sqrt(n+0.0); i++)
    {
        while(n%i==0)
        {
            top++;
            factor[top]=i;
            n/=i;
        }
    }
    if(n!=1)
    {
        top++;
        factor[top]=n;
    }
    for(int i=1; i<=top-1; i++)
    {
        printf("%d*",factor[i]);
    }
    printf("%d\n",factor[top]);
    return ;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        top=0;
        divide(n);
    }
    return 0;
}
View Code

相关文章:

  • 2021-09-06
  • 2020-03-22
  • 2022-12-23
  • 2019-03-03
  • 2021-08-05
  • 2022-12-23
  • 2022-02-05
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案