HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Project Euler #3 In C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
projecteulerstackoverflow

Problem

The question for reference:


The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143?

answer: 6857

I'm looking for general feedback as to style and particularly usage of the STL. Efficiency is a concern but a simple link to a better algorithm will suffice.

#include 
#include 
#include 

template 
std::list TrialFactorization(T n) {
    std::list base_factors;
    if(n == 1 || n == 2)
        base_factors.push_back(n);
    for(T p = 2; p  my_base_factors = TrialFactorization(my_int);
    // std::cout << *std::max_element(my_base_factors.begin(), my_base_factors.end());
    // Exploit sorted.
    std::cout << (* --my_base_factors.end());
}

Solution

You can improve the performance of the inner divisibility test by using std::div to do the division and modulo operations in one step. The following should work:

for (;;) {
        auto r = std::div(n, p);
        if (r.rem != 0) {
            break;
        }
        n = r.quot;
        base_factors.push_back(p);
    }


The return value of std::div is a type such as std::lldiv_t (the exact return type ultimately depends on the template type parameter T).

Code Snippets

for (;;) {
        auto r = std::div(n, p);
        if (r.rem != 0) {
            break;
        }
        n = r.quot;
        base_factors.push_back(p);
    }

Context

StackExchange Code Review Q#73360, answer score: 5

Revisions (0)

No revisions yet.