Advertisement
skb50bd

LCM-GCD

Aug 31st, 2015
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.24 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5.     int arr[10] = {0}, n, LG, LCM, GCD, i, j;
  6.  
  7.     while(true) {
  8.         cout << "OPERATIONS" << endl;
  9.         cout << "1. LCM (Lowest Common Multiple)" << endl;
  10.         cout << "2. GCD (Greatest Common Divisor)" << endl;
  11.         cout << "0. Exit." << endl;
  12.         cout << "Enter Choice: ";
  13.         cin >> LG;
  14.  
  15.         if(LG == 1 || LG == 2) {
  16.             while(true) {
  17.                 cout << "How Many Elements? (Maximum 10) : ";
  18.                 cin >> n;
  19.                 if(n > 10 || n < 1)
  20.                     cout << "Invalid Input. Try Again." << endl;
  21.                 else
  22.                     break;
  23.             }
  24.             cout << "Enter the Elements (Only Non-Zero Positive Integers): ";
  25.  
  26.             for(i = 0; i < n; i++)
  27.                 cin >> arr[i];
  28.             LCM = 9999, GCD = -1;
  29.             for(i = 0; i < n; i++) {
  30.                 while(true) {
  31.                     if(arr[i] < 1) {
  32.                         cout << "Element no. " << i + 1 << " is invalid. Renter The Element: ";
  33.                         cin >> arr[i];
  34.                     }
  35.                     else {
  36.                         if(arr[i] < LCM) LCM = arr[i];
  37.                         if(arr[i] > GCD) GCD = arr[i];
  38.                         break;
  39.                     }
  40.                 }
  41.             }
  42.  
  43.             if(LG == 1) {
  44.                 for(i = LCM; ; i++) {
  45.                     for(j = 0; j < n; j++)
  46.                         if(i % arr[j] != 0) break;
  47.                     if(j == n) {
  48.                         LCM = i;
  49.                         break;
  50.                     }
  51.                 }
  52.                 cout << "LCM = " << LCM << endl << endl << endl;
  53.             }
  54.  
  55.             else {
  56.                 for(i = GCD; i > 0; i--) {
  57.                     for(j = 0; j < n; j++)
  58.                         if(arr[j] % i != 0) break;
  59.                     if(j == n) {
  60.                         GCD = i;
  61.                         break;
  62.                     }
  63.                 }
  64.                 cout << "GCD = " << GCD << endl << endl << endl;
  65.             }
  66.         }
  67.         else if(LG == 0) break;
  68.  
  69.         else cout << "Invalid Choice. Try Again." << endl << endl;
  70.  
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement