Finding prime factors

前端 未结 12 598
北海茫月
北海茫月 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 14:44

    A C++ implementation using @user448810's pseudocode:

    #include 
    using namespace std;
    
    void factors(long long n) {
        long long z = 2;
        while (z * z <= n) {
            if (n % z == 0) {
                cout << z << endl;
                n /= z;
            } else {
                z++;
            }
        }
        if (n > 1) {
            cout << n << endl;
        }
    }
    
    int main(int argc, char *argv[]) {
        long long r = atoll(argv[1]);
        factors(r);
    }
    
    // g++ factors.cpp -o factors ; factors 600851475143
    

    Perl implementation with the same algorithm is below.
    Runs ~10-15x slower (Perl 0.01 seconds for n=600851475143)

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    sub factors {
        my $n = shift;
        my $z = 2;
        while ($z * $z <= $n) {
            if ( $n % $z ) {
                $z++;
            } else {
                print "$z\n";
                $n /= $z;
            }
        }
        if ( $n > 1 ) {
            print "$n\n"
        }
    }
    
    factors(shift);
    
    # factors 600851475143
    

提交回复
热议问题