Largest prime factor


/ Published in: C++
Save to your folder(s)

This code finds the largest prime factor in any given integer (within the bounds of a long long int)


Copy this code and paste it in your HTML
  1. #include <iostream>
  2.  
  3. unsigned long long int largestPrimeFactor(long long int N)
  4. {
  5. if (N < 0)
  6. N = -N;
  7.  
  8. if (N == 0 || N == 1)
  9. return 0;
  10.  
  11. long long int i;
  12. for (i = 2; i < N; ++i)
  13. if (N % i == 0)
  14. return largestPrimeFactor(N / i);
  15.  
  16. return i;
  17. }
  18.  
  19. void main()
  20. {
  21. long long int n;
  22. std::cout << "Please enter any integer (negative numbers will be treated as positive):" << std::endl;
  23. std::cin >> n;
  24. std::cout << "The largest prime factor of " << n << " is " << largestPrimeFactor(n) << std::endl;
  25. system("pause");
  26. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.