Will Clausen's Website

Categories
WCW

Kaprekar Numbers

Below is my solution to the Programming Praxis problem from Sept. 21, 2010. The problem was to find all Kaprekar numbers less than 1000. I wrote my solution in C++ to refresh my skills a little. For more info, seeĀ this link.


// Author: William Clausen
// Date: Aug. 10, 2014
// Description: Programming Praxis problem from Sep. 21, 2010

// Write a program to determine Kaprekar numbers less than a given input

#include <vector>
#include <iostream> // for testing in main
#include <cmath> // for pow

using namespace std;

// Helper function that returns a power of 10 where the exponent is equal
// to the number of digits in number
int numDigits(int number) {
	int result = 1;

	// Next, add the appropriate number of zeros to the result.
	while (result < number) {
		result *= 10;
	}

	return result;
}

// Helper function that returns true if the input is a Kaprekar number and
// false otherwise.
bool isKaprekar(int number) {
	int square = pow(number, 2);

	// We need to know the number of digits in the input so figure that out.
	// Get a power of ten where the exponent equals the number of digits
	int modulo = numDigits(number);

	// Get the last n digits of the square
	int lastNDigits = square % modulo;

	// Get the first n or n-1 digits
	int firstDigits = square / modulo;

	// Add these numbers to determine if it's a Kaprekar number
	if (lastNDigits + firstDigits == number) {
		return true;
	}

	return false;
}

// Function that returns a vector of all Kaprekar numbers less than the input.
vector<int> kaprekar(int limit) {
	// Create the vector of Kaprekar numbers to be returned
	vector<int> result;

	// Loop through all the numbers and if they are kaprekar numbers, add them
	// to the vector.
	for (int i = 0; i < limit; ++i) {
		if (isKaprekar(i)) {
			result.push_back(i);
		}
	}

	return result;
}

int main() {
	// Determine the Kaprekar numbers less than 1000.
	vector<int> answer = kaprekar(1000);

	cout << "The Kaprekar numbers less than 1000 are: ";
	for (int i = 0; i < answer.size(); ++i) {
		cout << answer[i] << ", ";
	}
	cout << "\n";
}

Leave a Reply

Your email address will not be published. Required fields are marked *