Thursday 15 January 2015

c - spoj factorial (time limit exceeded error). How can i improve my solution? -


Here is a link to my question.

I repeat it again, but I am getting an error in crossing the deadline. How can I improve my solution?

I have shown both solutions below.

A) Non-recurring approaches.

  #include & lt; Stdio.h & gt; Int main () {Long long int t, n, i, j = 0, y; Unsigned long-time facts; Scanf ("% lld", & amp; t); I = t; While (i & gt; 0) {scanf ("% lld", & amp; n); Fact = 1; For (y = 1; y and lt; = n; y ++) fact = fact * y; J = 0; While (fact% 10 == 0) j ++; Printf ("\ n% lld", j); I--; } Return 0; }   

b) non-recursive

  #include & lt; Stdio.h & gt; Unsigned long long intestinal phenomena (long int); Int main () {long long int t, n, i, j = 0; Unsigned long int y; Scanf ("% lld", & amp; t); I = t; While (i & gt; 0) {scanf ("% lld", & amp; n); Y = fact (n); J = 0; While (y% 10 == 0) j ++; Printf ("\ n% lld", j); I--; } Return 0; } Unsigned long-lasting fact (long-term) (if (m == 0) returns 1; and return (m * fact (m -1);}    

This problem reduces get strength of n in 10 (factorial of n), but for this we need 2 And the power of 5 will be achieved, as 10 prime ministers decrease in 2 and 5

  k1 = [n / 2] + [N / 4] + [n / 8] + [N / 16] + .... k2 = [n / 5] + [n / 25] + [n / 125] + [n / 625] + ... where [x] is the largest integer task k1 In = 2 Power of N! Power of N in K2 = 5! Answer = min (k1, k2)   

But the problem is that we still calculate the power of 2 and 5. That How to avoid? Since we have to divide by power.

  for 1 2, sum = 0 2. 2 (sum + = n / 2 and n = n / 2) Continue dividing by 2. 3. And keep adding quotient to the sum until n becomes 0. 4. At the end, yoga 2 will give strength to the inn!   

Repeat this for 5 , And there will be minimal answer between the two.

Job Code:

  // Shashank Jain #include  gt;) {temp = m / num; yoga = floating; m / = number;} return amount;} Int main () {int t; ll1, k2, nan; scanf ("% d", & amp; t); while (t--) {scanf ("% lld", & amp; n); k1 = Power (2); k2 = power (5); ans = minute (k1, k2); printf ("% lld \ n", ans);} return 0;}   

Running code link:

I just got 0.54 seconds and 2.6 MB

No comments:

Post a Comment