[2015-05-18] Challenge #215 [Easy] Sad Cycles

I thought about this for a bit while going to the bathroom. I even added a bit of error handling for bad input types! Here it is, written in C++. My method uses log to find the number of digits, and then uses division and powers of 10 to isolate each individual digit and put it into the next number in the cycle.

#include <iostream>
#include <limits>
#include <cmath>

int main(int* argc, char** argv) {
    signed int b;           //base
    signed int seed;        //starting value
    signed int numcycles;   //number of times to run the cycle
    int digit;              //Current digit value being handled. For the loop later on.
    int numdigits;          //Total number of digits. For the loop later on
    signed int newseed = 0; //Value to store the next value in the cycle before resetting the loop

    //Get b, error-check
    std::cout << "Please enter your base: ";
    while (!(std::cin >> b)) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input. Please re-enter your base: ";
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    //Get seed
    std::cout << "Please enter your seed: ";
    while (!(std::cin >> seed)) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input. Please re-enter your seed: ";
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    //Get numcycles
    std::cout << "Please enter the desired number of iterations: ";
    while (!(std::cin >> numcycles)) {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        std::cout << "Invalid input. Please re-enter your desired number of iterations: ";
    }
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

    //Echo all these values back
    std::cout << "Performing "<< b << "-sad cycle on " << seed << " for " << numcycles << " time(s)." << std::endl;

    //Calculate
    for (int j = 0; j < numcycles; j++) {
        numdigits = floor(log10(seed)) + 1;
        for (int i = numdigits - 1; i >= 0; i--) { //Incrememnt backwards to do the sad cycle and then take the last number off the top
            digit = floor(seed / pow(10, i));
            newseed += pow(digit, b);
            seed -= digit*pow(10, i);
        }
        seed = newseed;
        newseed = 0;
        std::cout << seed << ", ";
    }
    std::cout << std::endl;
    system("pause");
    return 0;
}
/r/dailyprogrammer Thread