Guest User

Blackone

a guest
Nov 15th, 2009
300
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. // 3nplus1problem.cpp
  2. // Author: Jose E Cartagena Alicea
  3. // Date: April 22, 2009
  4.  
  5. #include <iostream>
  6. #include <fstream>
  7. using namespace std;
  8.  
  9.  
  10.  
  11. // Prototypes
  12. void readFile(int &n1, int &n2, ifstream &inFile);
  13. void writeFile(int n1, int n2, int max, ofstream & outFile);
  14. int checkIterations(int n1, int n2);
  15. int iterations(int value);
  16.  
  17. int main()
  18. {
  19.     ifstream inFile;
  20.     ofstream outFile;
  21.     int n1, n2;
  22.    
  23.     try
  24.     {
  25.     inFile.open("input.in");
  26.     outFile.open("output.out");
  27.     }
  28.     catch(...)
  29.     {
  30.         cout << "Files can not be opened\n";
  31.         cin.ignore();
  32.         return 1;
  33.     }
  34.        
  35.     readFile(n1, n2, inFile);  
  36.     while(!inFile.eof())
  37.     {
  38.         int max = checkIterations(n1, n2);
  39.         writeFile(n1, n2, max, outFile);
  40.         readFile(n1, n2, inFile);
  41.     }
  42.    
  43.     cout << "Finishing the problem\n";
  44.     cin.ignore();
  45.     inFile.close();
  46.     outFile.close();
  47.     return 0;
  48. }
  49.  
  50. // This function is to read the data from the file called input.in
  51. void readFile(int &n1, int &n2, ifstream &inFile)
  52. {
  53.     try
  54.     {
  55.         inFile >> n1 >> n2;
  56.     }
  57.     catch(...)
  58.     {
  59.         cout << "The expression was in an incorrect format\n";
  60.     }
  61. }
  62.  
  63. // This function is to write the results into the file output.out
  64. void writeFile(int n1, int n2, int max, ofstream &outFile)
  65. {
  66.     outFile << n1 << " " << n2 << " " << max << endl;
  67. }
  68.  
  69. // This function call the function iterations to check the iterations of
  70. // each number then compare them to return the greater value
  71. int checkIterations(int n1, int n2)
  72. {
  73.     int max = 1;
  74.     for(int i = n1; i <= n2; i++)
  75.     {
  76.         int temp = iterations(i);
  77.         if(temp > max)
  78.             max = temp;
  79.     }
  80.     return max;
  81.    
  82. }
  83.  
  84. // This module checks the iterations of the value sended to it
  85. int iterations(int value)
  86. {
  87.     int count = 1;
  88.     while(value != 1)
  89.     {
  90.         if(value % 2 == 0)
  91.             value = value / 2;
  92.         else
  93.             value = value * 3 + 1;
  94.        
  95.         count ++;
  96.     }
  97.     return count;
  98. }
  99.    
Advertisement
Add Comment
Please, Sign In to add comment