fbpx

C++: Harshad/Niven Series

Bjarne-stroustrup
 

The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits.

For example, 42 is a Harshad number as 42 is divisible by (4+2) without remainder. Assume that the series is defined as the numbers in increasing order.

The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000.

#include <vector>
#include <iostream>

int sumDigits ( int number ) {
	int sum = 0 ;
	while ( number != 0 ) {
		sum += number % 10 ;
		number /= 10 ;
	}
	return sum ;
}

bool isHarshad ( int number ) {
	return number % ( sumDigits ( number ) ) == 0 ;
}

int main( ) {
	std::vector<int> harshads ;
	int i = 0 ;
	while ( harshads.size( ) != 20 ) {
		i++ ;
		if ( isHarshad ( i ) ) 
		harshads.push_back( i ) ;
	}
	std::cout << "The first 20 Harshad numbers:\n" ;
	for ( int number : harshads )
	std::cout << number << " " ;
	std::cout << std::endl ;
	int start = 1001 ;
	while ( ! ( isHarshad ( start ) ) ) 
	start++ ;
	std::cout << "The smallest Harshad number greater than 1000 : " << start << '\n' ;
	return 0 ;
}
Output:
The first 20 Harshad numbers:
1 2 3 4 5 6 7 8 9 10 12 18 20 21 24 27 30 36 40 42 
The smallest Harshad number greater than 1000 : 1002

SOURCE

Content is available under GNU Free Documentation License 1.2.