integer overflow.

hello i am making a program (project euler #3) that should find the biggest prime factor of 600851475143. but when i do something like.long unsigned int number=600851475143; it still overflows and gives me a wrong answer.
when i use like long double i can't use the % anymore so then i am stuck again.
could someone tell me what i should do here.
my code here:
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <math.h>

bool isPrime (int num)
{
    if (num <=1)
        return false;
    else if (num == 2)         
        return true;
    else if (num % 2 == 0)
        return false;
    else
    {
        bool prime = true;
        int divisor = 3;
        double num_d = static_cast<double>(num);
        int upperLimit = static_cast<int>(sqrt(num_d) +1);
        
        while (divisor <= upperLimit)
        {
            if (num % divisor == 0)
                prime = false;
            divisor +=2;
        }
        return prime;
    }
}

int main() {
	long unsigned int number=600851475143;
	//int number=270;
	for (int i=2;;i++) {
		if (!isPrime(i)) {
			continue;
		} else {
		
		while(number%i==0) {
			number/=i;
			std::cout<<i<<"   "<<number<<std::endl;
		}
		}
		if(number==1) {
			std::cout<<"finished:"<<i<<std::endl;
			break;
		}
		
	}
	system("pause");
	return 0;
}
Last edited on
Try 600851475143UL or 600851475143ULL maybe?
um now i have tried long unsigned long number; but it still fails.
it is telling me 600851475143%3==0 but it should be equal to 2
Last edited on
got it now. i have just removed the % and made my own.
Topic archived. No new replies allowed.