Finding prime factors

前端 未结 12 602
北海茫月
北海茫月 2020-12-29 14:24
#include 
using namespace std;

void whosprime(long long x)
{
    bool imPrime = true;

    for(int i = 1; i <= x; i++)
    {
        for(int z =          


        
12条回答
  •  南笙
    南笙 (楼主)
    2020-12-29 15:04

    Here is my code that worked pretty well to find the largest prime factor of any number:

    #include 
    using namespace std;
    
    // --> is_prime <--
    // Determines if the integer accepted is prime or not
    bool is_prime(int n){
        int i,count=0;
        if(n==1 || n==2)
          return true;
        if(n%2==0)
          return false;
        for(i=1;i<=n;i++){
        if(n%i==0)
            count++;
        }
        if(count==2)
          return true;
        else
          return false;
     }
     // --> nextPrime <--
     // Finds and returns the next prime number
     int nextPrime(int prime){
         bool a = false;
         while (a == false){
             prime++;
             if (is_prime(prime))
                a = true;
         }
      return prime;
     }
     // ----- M A I N ------
     int main(){
    
          int value = 13195;
          int prime = 2;
          bool done = false;
    
          while (done == false){
              if (value%prime == 0){
                 value = value/prime;
                 if (is_prime(value)){
                     done = true;
                 }
              } else {
                 prime = nextPrime(prime);
              }
          }
            cout << "Largest prime factor: " << value << endl;
     }
    

    Keep in mind that if you want to find the largest prime factor of extremely large number, you have to use 'long' variable type instead of 'int' and tweak the algorithm to process faster.

提交回复
热议问题