Why to find the factor of a number only need to judge its square root

Problem Description

When doing blue bridge cup algorithm questions, I found that there are often some simple questions, using the brute force method to traverse, but because the given parameters are too large, the running time is too long, so when simplifying the data, I often use the method of finding a number factor to simplify the algorithm. However, why do you only need to judge its square root when looking for a factor of a number?

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(){
    
    
    ll n =100;
    vector<ll> a;

    for(int i = 1; i <=sqrt(n); i++){
    
    
        if(n % i == 0){
    
    
            a.push_back(i);
            if(i*i != n){
    
    
                a.push_back(n/i);
            }
        }
    }

    for(ll i=0;i<a.size();i++){
    
    
        cout<<a[i]<<" ";
    }

    return 0;
}


Cause Analysis:

For example: 25, after the square root is 5, then it can be divisible by 2~5, if there is a number that meets the conditions, it is a prime number. And the factors are 1, 25, 5. When the traversal finds that 1 is divisible by 25, that is, 25%1=0, then 25/1=25 must also be a factor of 25. Therefore, when looking for factors, you only need to traverse to the square root of n to find all the factors of n.

Guess you like

Origin blog.csdn.net/qq_38786110/article/details/129899782