one of the Fastest way to find factors of a Number

Revision en2, by The-Madara-uchiha, 2024-05-10 02:11:09

// Sometimes, we need to find factors of a number to solve a problem. There are many ways to find factors of a number. Here, I am sharing a code :

vector<int> factors; // vector is a dynamic array , which size is not fix

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



// First, we are using a vector because we don't know the size.
// Then, we are using a for loop up to the square root of that number.
// Then, we are using two conditions to add factors. The first condition adds factors before the square root, and the second one adds factors after the square root.
Tags math, number theory

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English The-Madara-uchiha 2024-05-10 02:38:37 88
en2 English The-Madara-uchiha 2024-05-10 02:11:09 7 Tiny change: '}\n }\n // F' -> '}\n }\n\n\n\n // F'
en1 English The-Madara-uchiha 2024-05-10 02:10:38 778 Initial revision (published)