Unknown trouble with short code for Project Euler Problem 3.

I am a new c++ programmer currently working through project Euler, and I've gotten myself stuck on problem 3: find the greatest prime factor of 600851475143.
My friend and I came up with the idea to create this "for" loop, where n is the large integer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include <iostream>
using namespace std;
int main()
{
   long long n;
   cout << "please input a number" << endl;
   cin >> n;
   int limit = (n/2)+1;
   //no prime factor can exceed half the value
   int biggest = n;
   //initializing biggest to n
   for (int i = 2; i < limit; i++)
   {   
       while (n%i==0)
       {
        biggest = n;
        n = n/i;
       }
       // for every integer that divides evenly into n, divide n by that integer until it does not divide evenly any more. Then, iterate i, and store the biggest value obtained in c. When n=1, c is the greatest prime factor.
   }
cout << biggest << endl;
return 0;
//display c and end the program
}


This should ostensibly give the largest prime factor of n. However, when Project Euler's number is the input, it returns 151, which Euler says is wrong.
Is there any way, (without doing my work for me of course), that someone could point me in the direction of my error?
truncating errors.

you're trying to stick a 64-bit number into an int. You need to make i, biggest, and limit all long long like 'n' is.
is that supposed to greatly increase the runtime? because it is taking a while.
well you're looping 300425737572 times. So yeah that's going to take really, really, really long.

Rather than looping to 'limit', maybe loop to 'n' instead. Since 'n' is being reduced as you find divisors.
It worked instantly but gave 10086647, which Euler says is wrong...
<n ? or <=n ?
there we go! using <= n solved it.
...Is that because when the program gets down to the prime factor, i = the decreased n?
Topic archived. No new replies allowed.