Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <math.h>
- unsigned long largestPrimeFactor(unsigned long n);
- int main(void)
- {
- unsigned long n;
- printf("please enter a number to find the largest prime factor:\n");
- scanf("%lu", &n);
- printf("\n\nThe largest prime factor is: %lu\n",
- largestPrimeFactor(n));
- return 0;
- }
- unsigned long largestPrimeFactor(unsigned long n)
- {
- unsigned long x = (unsigned long) sqrt(n);
- while (n % x != 0)
- x--;
- // x is a factor (may be prime or composite)
- // and splits n into its largest divisions
- if (x == 1)
- {
- printf("Found a prime! %lu\n", n);
- return n; // n is prime
- }
- unsigned long s = largestPrimeFactor(x);
- unsigned long t = largestPrimeFactor(n/x);
- return ((s > t) ? s : t); // return larger value
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement