Hi,
I'm trying to write a program that will take in an integer N, then, starting from N, loop to a limit of 1 billion, printing the first harshad number that is greater than or equal to N.
A quick explanation of a harshad number is any number than is divisible by the sum of its digits. e.g. 156 (1+5+6)= 12 (156/12)= 13.
e.g.
24 would output 24 since 24 / 6 = 4.
25 would output 27 since 27 / 9 = 3 and it's the next harshad number after 25.
However, my code only checks to see if N is a harshad number. If it is, it will print it out, otherwise it's in an infinite loop.
I'm dealing with unsigned long long ints and converting back and forth from strings, which, I'm very unfamiliar with. I've provided some comments, but I am sure I am not explaining things properly, so I'll address any confusion.
Can anyone help me see why my code won't loop until it finds the next number that's a harshad number?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <string>
using namespace std;
int main(){
unsigned long long int sumofdigits = 0; // this will add up the digits of
//number. e.g. 24 = 6
string numtostring;
unsigned long long int tot;
cin >> tot;
for (unsigned long long int k = tot; k < 1000000000 + 1; k++) {
string g = to_string(k); // i don't know how to add integer digits
//together so I turn it into a temp string
string pw[g.length()]; //create an array to store the individual
//elements of the integer to string
for (unsigned long long int i = 0; i < g.length(); i++){
pw[i] = g[i]; // filling the array with the digits separated
}
unsigned long long int yy[g.length()]; // an array to turn them back
//into separate integers
for (unsigned long long int i = 0; i < g.length(); i++) {
yy[i] = stoull(pw[i]); // converting them and storing them
}
for (unsigned long long int i = 0; i < g.length(); i++) {
sumofdigits += yy[i]; // e.g. turning 24 into 2 + 4 = 6
}
if (k % sumofdigits == 0){ // checking to see if harshad number. e.g.
//24 % 6 = 0
cout << k;
return 0;
}
}
}
|
**This is not homework.It's not a ranked competition. It's a practice challenge from a programming challenge site designed to help students learn to think the way they will need to think in the workforce.**