program that finds results of two digits python
Write a program that finds two digit A and B (dont search the web, and dont try 'manually') so that we get a two digit number AB (say A = 8, B = 9 then the number is 89) and so that AB*AB = CAB for some digit C. Thus if you square AB you get a 3 digit number. The two last digits in AB^2 are AB but the fir开发者_JS百科st digit is some C that may not related necessarily to A or B.
In pseudo-code, you could simply do something like:
def findAB (c):
c = c multiplied by 100
for a in 0..9: # or possibly 1..9
for b in 0..9:
set ab to a multiplied by 10 plus b
if (ab multiplied by ab) is equal to (c plus ab):
return (a,b)
return nothing
My preferred language for pseudo-code is close enough to Python that it shouldn't be too hard to convert but your first step should be understanding how it works. To that end you should run the code in your head, filling out a variable sheet like:
c | a | b | ab | return
-----+-----+-----+------+----------
| | | |
| | | |
| | | |
| | | |
The sooner you start thinking like a machine, the better a programmer you'll become - just make sure you don't boot out all those social skills though, they'll still come in handy at certain points in your life :-)
Simply, in code:
for a in range(1,10):
for b in range(10):
ab = a*10+b
ab2 = ab*ab
if (ab2 % 100) == ab:
print "a=",a,", b = ",b
As an alternative to brute force, take two minutes and think about the problem. Think about A - what is the smallest number A could be? What is the largest? Think about B - there is something special about B, some special property that only 4 of the total 10 digits have. In the end, you will still have to loop over a couple of sets of numbers for A and B, but if you use only the set of likely numbers, you will show that you have put some intelligent thought into your solution. And as I said before, this problem generalizes to some interesting larger cases, for instance, you can find a number ABCDEF which, when squared gives ######ABCDEF.
Bonus: do you think there is a largest possible number that has this property?
精彩评论