Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3. #include <sstream>
  4. using namespace std;
  5.  
  6. static int firstFactorDigits;
  7. static int secondFactorDigits;
  8. int LargestPalindromicProduct(int firstFactorDigits, int secondFactorDigits);
  9.  
  10. int main() {
  11. cout << "Enter the number of digits you want for the first factor:";
  12. cin >> firstFactorDigits;
  13. cout << "Enter the number of digits you want for the second factor:";
  14. cin >> secondFactorDigits;
  15. cout << "Largest Palindromic Product: " << LargestPalindromicProduct(firstFactorDigits, secondFactorDigits);
  16. return 0;
  17. }
  18.  
  19. bool CheckForPalindrome(int product) {
  20. ostringstream productAsString;
  21. productAsString << product;
  22. string productParsedAsString = productAsString.str();
  23. int backwardsProductParsedAsStringPosition = productParsedAsString.length() - 1;
  24. string backwardsProductParsedAsString;
  25. for (int currentChar = 0; currentChar < productParsedAsString.length(); currentChar++) {
  26. backwardsProductParsedAsString += productParsedAsString.at(backwardsProductParsedAsStringPosition);
  27. backwardsProductParsedAsStringPosition--;
  28. }
  29. if (productParsedAsString == backwardsProductParsedAsString)
  30. return true;
  31. return false;
  32. }
  33.  
  34. int LargestPalindromicProduct(int firstFactorDigits, int secondFactorDigits) {
  35. static int LargestPalindromicProduct = 0;
  36. for (int currentFirstProduct = 1; currentFirstProduct < pow(10, firstFactorDigits); currentFirstProduct++) {
  37. for (int currentSecondProduct = 1; currentSecondProduct < pow(10, secondFactorDigits); currentSecondProduct++) {
  38. if (CheckForPalindrome(currentFirstProduct * currentSecondProduct) && currentFirstProduct * currentSecondProduct > LargestPalindromicProduct)
  39. LargestPalindromicProduct = currentFirstProduct * currentSecondProduct;
  40.  
  41. }
  42. }
  43. return LargestPalindromicProduct;
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement