Hello,
I know that this topic is a bit old, but I decided to give it a go again after my earlier "fumble".
I decided to use a factor tree method (one of the many tidbits of information that I managed to remember from school) and wrote this:
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
|
/*
Calculates the highest prime factor of int number types.
*/
#include <iostream>
#include <cmath>
using namespace std;
bool checkprime(int k);
int lpd( int a);
int main() { int a;
cout << "Calculates the largest prime that divides a number.\n";
cout << "Enter a number: ";
cin >> a;
while(!(checkprime(a))) { a = a / lpd(a); }
cout << a << '\n';
return 0;
}
//Outputs 1 if k is prime, 0 if it is not prime.
bool checkprime(int k){ bool b = 1;
if(k == 2) return 1;
for(int i=2; i <= pow(k, 0.5); i++){ if(!(k%i)) b=0; }
return b; }
//Outputs the lowest prime number that divides a (lowest prime divisor).
int lpd(int a){ for(int i=2;i <= a / 2;i++){ if(!(a%i) && checkprime(i)) return i; }
return a;
}
|
It works like this:
1). Takes the number you enter (say a).
2). Finds the lowest prime that divides this number (say p).
3). Lets a = a/p.
4). Goes back to step 1, or terminates if a is prime.
5). Outputs this new prime a.
It seems to work with small numbers:
Calculates the largest prime that divides a number.
Enter a number: 8935
1787
|
However, it doesn't work for the large number that started this thread!
If I change the int in the function lpd, and the int in the main function (to unsigned long long int) I get an error message:
/tmp/ccIub14M.o: In function `main':
bignum1.cpp:(.text+0x61): undefined reference to `lpd(unsigned long long)'
collect2: ld returned 1 exit status |
Is there any way to pass an unsigned long long int into this program?
(P.S: It would be finally nice for me to solve this question once and for all!).