Friday, September 19, 2014
Vaishnav and Factorials
Problem
Idea : Given an integer N . You have to do the following tasks-
1 . Calculate the factorial of N .
2 . Count how many 4 or 7 are in N!
To do the first task -
You have to calculate N! . Very simple . Wait , the range of N from 1 to 250 . Using built in data type , you can calculate factorial up to 20 . Then ?
Now , you have to think something new . To face this situation , we can use array . In an array , we will keep a value . In every cell of the array , we will keep every digit of the value . Now think about calculating factorial as below -
factorial = 1 ;
for(int i=1;i<=N;i++)
factorial*=i ; // Multiplication to calculate factorial
For an array , we will multiply with array cell start from starting .
Initially we assign array[0] = 1 , and carry = 0 . Then for every value comes in the loop , we will multiply with every cell and add carry . Then the last digit of the value will remain in current position of the array . The carry is value/10 . After multiplying , we keep the carry infront of the array . Thus , if we iterate till N . We will get factorial in the array .
To do the second task -
Iterate from the starting of the array to the last and increase counter if array[i]==4 or array[i]==7 .
Then print the value of counter .
My Solution
Labels:
Number Theory
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment