Egor_Vakar

lab2_2(C++)

Oct 13th, 2021 (edited)
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.30 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int takeCoefficientValue() {
  5.     bool isIncorrect;
  6.     int number = 0;
  7.     cout << "Enter k value: ";
  8.     bool isInсorrect;
  9.     do{
  10.         isInсorrect = false;
  11.         cin >> number;
  12.         if (!cin.good()){
  13.             isInсorrect = true;
  14.             cout << "Incorrect input!!!\nEnter k value: ";
  15.             while (cin.get() != '\n') {
  16.                 cin.clear();
  17.             }
  18.         }
  19.         if ((!isInсorrect) && (number < 1)){
  20.             isInсorrect = true;
  21.             cout << "The number must be more than 0\nEnter k value: ";
  22.         }
  23.     } while (isInсorrect);
  24.     return number;
  25. }
  26.  
  27. static int findNumberOfAnswers(int coefficient) {
  28.     const int MAX = 1000000;
  29.     int counter = 0;
  30.     int current;
  31.     int figureTotal;
  32.     for (int i = 1; i < MAX; i++) {
  33.         current = i;
  34.         figureTotal = 0;
  35.         while (current > 0) {
  36.             figureTotal += current % 10;
  37.             current /= 10;
  38.         }
  39.         if (i == figureTotal * coefficient) {
  40.             counter++;
  41.         }
  42.     }
  43.     return counter;
  44. }
  45.  
  46. int *findArrayOfAnswers(int coefficient, int size) {
  47.     int *arrayOfAnswers = new int[size];
  48.     int MAX = 1000000;
  49.     int counter = 0;
  50.     int current;
  51.     int figureTotal;
  52.     for (int i = 1; i < MAX; i++) {
  53.         current = i;
  54.         figureTotal = 0;
  55.         while (current > 0) {
  56.             figureTotal += current % 10;
  57.             current /= 10;
  58.         }
  59.         if (i == figureTotal * coefficient) {
  60.             arrayOfAnswers[counter] = i;
  61.             counter++;
  62.         }
  63.     }
  64.     return arrayOfAnswers;
  65. }
  66.  
  67. void output(int number, int* array) {
  68.     if (number == 0) {
  69.         cout << "Answers are not found.";
  70.     }
  71.     else {
  72.         cout << "Answers are:\n";
  73.         for (int i = 0; i < number; i++) {
  74.             cout << array[i] << endl;
  75.         }
  76.     }
  77. }
  78.  
  79. int main()
  80. {
  81.     cout << "Welcome to the program that outputs all numbers, which are equal to the sum of their digits multiplied by k.\n";
  82.     int coefficient = takeCoefficientValue();
  83.     int numberOfAnswers = findNumberOfAnswers(coefficient);
  84.     int *arrayOfAnswers = findArrayOfAnswers(coefficient, numberOfAnswers);
  85.     output(numberOfAnswers, arrayOfAnswers);
  86.     delete[] arrayOfAnswers;
  87.     return 0;
  88. }
Add Comment
Please, Sign In to add comment