Why is it that some user defined C++ functions won't work with big numbers?

117 Views Asked by At

Here's an example:

This function won't work with big numbers such as 900000000 but will work with smaller numbers like 800

code:

#include <vector>
#include <iostream>
#include <string> using namespace std;


long long int largest_prime_factor(long long int num){
    vector<long long int >factors;
    vector<long long int>primes;
    for(long long int i=1;i<=num;i++){
        if(num%i==0){
            for(long long int a =1;a<=i;a++){
                if(i%a==0){
                    factors.push_back(a);
                }

            }
            if( (factors.size() == 2) && (factors[0] ==1)){
                primes.push_back(i);
            }
            factors.clear();
        }
    }
    reverse(primes.begin(),primes.end());
    return primes[0]; }

int main(){
    cout<<largest_prime_factor(600851475143)<<endl;
}
1

There are 1 best solutions below

1
On

Try invoking the function with the following code:

cout<<largest_prime_factor(600851475143LL)<<endl; 

If you simply mention the literal 600851475143, it wont be recognized as long long. you have to explicitly tell the compiler that treat the literal as long long by appending 'LL' at the end.