Advertisement
Guest User

Untitled

a guest
Jun 22nd, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.77 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. unsigned long largestPrimeFactor(unsigned long n);
  5.  
  6. int main(void)
  7. {
  8.     unsigned long n;
  9.    
  10.     printf("please enter a number to find the largest prime factor:\n");
  11.     scanf("%lu", &n);
  12.  
  13.     printf("\n\nThe largest prime factor is: %lu\n",
  14.         largestPrimeFactor(n));
  15.  
  16.     return 0;
  17. }
  18.  
  19. unsigned long largestPrimeFactor(unsigned long n)
  20. {
  21.     unsigned long x = (unsigned long) sqrt(n);
  22.  
  23.     while (n % x != 0)
  24.         x--;
  25.  
  26.     // x is a factor (may be prime or composite)
  27.     // and splits n into its largest divisions
  28.  
  29.     if (x == 1)
  30.     {
  31.         printf("Found a prime! %lu\n", n);
  32.         return n;  // n is prime
  33.     }
  34.  
  35.     unsigned long s = largestPrimeFactor(x);
  36.     unsigned long t = largestPrimeFactor(n/x);
  37.  
  38.     return ((s > t) ? s : t); // return larger value
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement