Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.61 KB | None | 0 0
  1. // collatzfile.cpp
  2. // Andrew Cummins
  3. // 21 Oct 2016
  4. // Program that will take users input of two integers and write collatz sequence between the two integers in a txt file
  5.  
  6. #include <iostream>
  7. using std::cout;
  8. using std::endl;
  9. using std::cin;
  10. #include <string>
  11. using std::string;
  12. using std::getline;
  13. #include <sstream>
  14. using std::istringstream;
  15. #include <fstream>
  16. using std::ofstream;
  17.  
  18. //function to handle the math and write to the file
  19. int collatz(int n)
  20. {
  21. // use ios_base::app to append the file instead of overwriting
  22. ofstream outfile("cseqs.txt", std::ios_base::app);
  23. if(!outfile)
  24. {
  25. // check if the file opened
  26. cout << "Could not open file" << endl;
  27. return 0;
  28. }
  29. outfile << n;
  30. while(n>1)
  31. {
  32. if(n%2==0)
  33. {
  34. n=n/2;
  35. outfile << ", " << n;
  36. }
  37. else
  38. {
  39. n=n*3+1;
  40. outfile << ", " << n;
  41. }
  42. }
  43. outfile << endl << endl;
  44. }
  45.  
  46. int main()
  47. {
  48. // loop to keep asking user for input
  49. while(true)
  50. {
  51. // ask for first integer
  52. cout << "Enter the first integer to begin a Collatz sequence: ";
  53. int number1;
  54. cin >> number1;
  55. if(!cin){ // error check
  56. return 0;
  57. }
  58. if(number1<0){ // make sure it is not negative
  59. cout << "Must be a positive number" << endl;
  60. continue;
  61. }
  62. cout << endl << endl;
  63. // ask for last integer
  64. cout << "Enter the last integer to begin a Collatz sequence: ";
  65. int number2;
  66. cin >> number2;
  67. if(!cin){ // error checking
  68. return 0;
  69. }
  70. if(number2<0){// make sure it is not negative
  71. cout << "Must be a positive number" << endl;
  72. continue;
  73. }
  74. cout << endl << endl;
  75. // make sure last integer is larger than first
  76. if(number1>number2)
  77. {
  78. cout << "The second integer must be at least as large as the first: try again" << endl;
  79. continue;
  80. }
  81. else
  82. {
  83. cout << endl << endl;
  84. cout << "Sequence beginning at " << number1 << " ... " << number2 << " successfully written to file 'cseqs.txt'" << endl;
  85. cout << endl << endl;
  86. // send each integer in the range to the function
  87. for(int i=number1; i<=number2; ++i)
  88. {
  89. collatz(i);
  90. }
  91. return 0; // end program once file is written
  92. }
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement