What is the smallest non-negative integer n for which n ! starts with the digit 9?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Here 's a C++ solution using a mathematical approach which is that the first digit of a positive integer n is given by,
First digit ( n ) = ⌊ 1 0 { lo g 1 0 ( n ) } ⌋
where { ⋅ } is the fractional part function and ⌊ ⋅ ⌋ is the floor function . Proving the above claimed formula is quite easy (using basic exponent laws and logarithm laws) and is left as an exercise to the reader.
Calculating factorials is expensive, and so is converting integers to strings. I therefore avoided both of these calculations. (Not that it matters in this case!)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
Ruby
def factorial(n)
i = n
until (i == 1) do
i -= 1
n = n * i
end
n
end
x = 0
h = 0
while x == 0 do
h += 1
a = factorial(h).to_s
if a[0] == "9"
x = 1
end
end
puts h
gets.chomp
1 2 3 4 5 |
|
Simple standard approach.
I have a mathlab/octave solution for those who are interested :
clear all;
format long
number = 0;
for i = 1 : 170
number = factorial(i);
do
number = number/10;
until (number <10)
if (floor(number) == 9)
disp ("The wanted number is :"), disp (i)
break;
endif
Problem Loading...
Note Loading...
Set Loading...