Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Squaring Each Digit of a 2 or 3 Digit Number 1

Status
Not open for further replies.

ICU2Desktop

Technical User
Jul 12, 2002
11
US

Hi, I'm trying to write a program that begins with a positive integer N and generates a sequence by the rule :
Ni+1 = sum of the squares of the digits of Ni. I need to know how to get all numbers that will return a 1, from 1 thru 99. I figure I can use pow to get the #'s to be squared, but I can not figure out how to square the first digit and then the second digit of a two digit #. Any help getting me started would be greatly appreciated. Thanks

 
I'm not sure if there's an easier or more efficient way to do it but you could:

// some example number
long egInt = 345;

// convert the number to a string and
// then convert each character of string back to number

char buffer[10];
_ltoa(egInt,buffer,10);

long digits[3];

for (int x=0;buffer[x];x++)
digits[x] = buffer[x]-48;

// by subtracting 48 from the ASCII value of
// each character, we get the numercial value of each
// digit in the string


If you convert the original number to a string you can then access each character of the number. By converting each character back to a number, you have the individual numbers in an array.

Obviously, you'll have to do something about the array size depending on the digits in the original number!
 
for an interger N set = to 45

pow( N / 10, 2 ) + pow ( N % 10, 2 );

is the sum of the squares of each digit 4 and 5.

For each power of 10 after 99 you will need an additional N / ? step if you want to make the program scalable.

Just for kicks, I wanna try to figure that out...

const int maxElements = ?;

int counter = 1,
N[ maxElements ] = ...,
size, //# digits in given N
count,
sum;

for( int i = 0; i < maxElements; i++, size = 1, count = 1 )
{
while( N[ i ]/ ( 10 * count++ ) > 0 ) //gets the # of
size++; //digits in N

//gets sum of squared first digit
sum = pow( N[ i ] % 10, 2 );

//gets the rest of Ni's^2
for( int j = 1; j < size; j++ )
sum += pow( ( N[ i ] / ( 10 * j ) ) % 10, 2 );

//do something with &quot;sum&quot;
}

I think that would make it scalable... haven't tested.


 
or like this :
i = N % 10
i = i * i
then divid by 10 and use integer-result
N = N / 10

then again
i = N % 10
i = i * i

and so on until division-result is less than 1.

by the way pow() is very slow !
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top