Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // 3nplus1problem.cpp
- // Author: Jose E Cartagena Alicea
- // Date: April 22, 2009
- #include <iostream>
- #include <fstream>
- using namespace std;
- // Prototypes
- void readFile(int &n1, int &n2, ifstream &inFile);
- void writeFile(int n1, int n2, int max, ofstream & outFile);
- int checkIterations(int n1, int n2);
- int iterations(int value);
- int main()
- {
- ifstream inFile;
- ofstream outFile;
- int n1, n2;
- try
- {
- inFile.open("input.in");
- outFile.open("output.out");
- }
- catch(...)
- {
- cout << "Files can not be opened\n";
- cin.ignore();
- return 1;
- }
- readFile(n1, n2, inFile);
- while(!inFile.eof())
- {
- int max = checkIterations(n1, n2);
- writeFile(n1, n2, max, outFile);
- readFile(n1, n2, inFile);
- }
- cout << "Finishing the problem\n";
- cin.ignore();
- inFile.close();
- outFile.close();
- return 0;
- }
- // This function is to read the data from the file called input.in
- void readFile(int &n1, int &n2, ifstream &inFile)
- {
- try
- {
- inFile >> n1 >> n2;
- }
- catch(...)
- {
- cout << "The expression was in an incorrect format\n";
- }
- }
- // This function is to write the results into the file output.out
- void writeFile(int n1, int n2, int max, ofstream &outFile)
- {
- outFile << n1 << " " << n2 << " " << max << endl;
- }
- // This function call the function iterations to check the iterations of
- // each number then compare them to return the greater value
- int checkIterations(int n1, int n2)
- {
- int max = 1;
- for(int i = n1; i <= n2; i++)
- {
- int temp = iterations(i);
- if(temp > max)
- max = temp;
- }
- return max;
- }
- // This module checks the iterations of the value sended to it
- int iterations(int value)
- {
- int count = 1;
- while(value != 1)
- {
- if(value % 2 == 0)
- value = value / 2;
- else
- value = value * 3 + 1;
- count ++;
- }
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment