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!

Trying to Square Each Digit of a Two Digit # 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
 
The code below should be what you are after, or give you enough hints to get what you need :

Code:
public class Test  {
  	public static void main (String args[]) {
		int n = 0, n1 = 0, n2 = 0, ni = 0;
		String sn = null;
		
		for (int i = n; i <= 99; i++) {
			n = i;
			if (n > 9) {						//if 'n' has two digits
				sn = (n +&quot;&quot;);   //force 'n' to a String
				n1 = Integer.parseInt(&quot;&quot; +sn.charAt(0));   //split the string into two char's 
				n2 = Integer.parseInt(&quot;&quot; +sn.charAt(1));   //and convert them to an int
				n1 = (n1 * n1);					//raise each in to a power
				n2 = (n2 * n2);

				ni = (n1 + n2);					//add the totals

				System.out.println(&quot;Orginal number is : &quot; +n +&quot;, first digit is : &quot; +n1 
						+&quot;, second digit is &quot; +n2 +&quot;, Sum is :&quot; +ni);
			}
			else {
				n1 = n;       				ni = (n * n);
				System.out.println(&quot;Orginal number is : &quot; +n +&quot;, first digit is : &quot; +n1 
						+&quot;, second digit is null&quot; +&quot;, Sum is :&quot; +ni);
			}

		}
	}
}

HTH,

Ben
 
Great, I'll play around with this and let you know. Thanks for the step in the right direction, I was stumped on how to even begin this.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top