考研算法 2022.3.2

130 阅读1分钟

考研算法

题目

题目链接

题目要求

分解质因数

代码

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
int main()
{
    LL n;
    cin>>n;
    LL res=1;
    for (LL i=2;i*i<=n;i++)
    {
        if (n%i==0)
        {
            int s=0;
            while (n%i==0)
            {
                s++;
                n=n/i;
            }
            if (s%2==1)
            {
                res=res*i;
            }
        }
    }
    if(n>1)
    {
        res=res*n;
    }
    cout<<res;
}
b=int(input())
res=1
for i in range(2,int(b**0.5)):
    if b%i == 0:
        s=0
        while(b%i==0): 
            s=s+1
            b=b/i
        if s%2==1:
            res=res*i
if b>0:
    res=res*b
print(int(res))

知识点

typedef

typedef long long LL对long long定义别名为LL\

寻找质因数代码

for (LL i=2;i*i<=n;i++)
    {
        if (n%i==0)
        {
            int s=0;
            while (n%i==0)
            {
                s++;
                n=n/i;
            }
            if (s%2==1)
            {
                res=res*i;
            }
        }
    }

LL的i很重要,否则i不可能列举到12位