Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main() not executing, but compiling

I have this simple program:

// Include libraries

#include <iostream>
#include <string>
#include <vector>

using namespace std;

// Include locals

// Start

#define NUMBER 600851475143

int main(int argc, const char* argv[])
{
    long long int ans = 0;
    long long int num = NUMBER;

    vector<int> factors;

    do
    {
        // Get lowest factor

        for (int i = 1; i <= num; ++i)
        {
            if (!(num % i))
            {
                factors.push_back(i);

                num /= i;
                break;
            }
        }
    } while (num > 1);

    cout << "Calculated to 1.\n";

    int highestFactor = numeric_limits<int>::min();

    for (int i = 0; i < factors.size(); ++i)
    {
        if (factors[i] > highestFactor)
        {
            highestFactor = factors[i];
        }
    }

    ans = highestFactor;

    cout << ans << endl;

    return EXIT_SUCCESS;
}

compiling with g++ -O2 -c -o prob3.o prob3.cpp proved successful, but when I ran it I saw nothing and it just kept running and I had to Ctrl-C (force-kill) it in the end. When I try to add

int main(int argc, const char* argv[])
{
    cout << "Test\n";

to the program, Test didn't get printed too. It's like my program is not executed at all.

Any help or advice is appreciated!

Solution

I forgot prime numbers started at 2. Change for (int i = 1 to for (int i = 2.

like image 927
ihsoy ih Avatar asked Dec 20 '12 15:12

ihsoy ih


3 Answers

Those nested loops are going to loop forever. The inner for loop will only ever execute once because of the break so it will only ever do num /= 1. That means num never decreases and so num > 1 will never be false. I suppose you just need to wait longer!

The reason you're not seeing "Test" is probably because you haven't flushed the output. Try:

std::cout << "Test" << std::endl;
like image 95
Joseph Mansfield Avatar answered Oct 23 '22 16:10

Joseph Mansfield


Your program is simply running. It takes a long time to execute.

For the cout << "Test\n";, it's a matter of the cout stream not being flushed: what you wrote to the stream is still in your program memory and not yet flushed to the system to be printed.

like image 32
Didier Trosset Avatar answered Oct 23 '22 15:10

Didier Trosset


Have you tried to start your for condition from 2? The module function doesn't have sense if start from 1.

if (!(num % i))

Num / 1 give 0, so you're not enter in the if condition

like image 1
Vargan Avatar answered Oct 23 '22 15:10

Vargan