We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Extra Long Factorials
Extra Long Factorials
yavuzselim + 0 comments Ppl posting java/python solutions as if they coded something challenging
tsuda_kageyu + 0 comments It's beyond my capacity to implement a complete BigInteger like class in C++, but I did this:
#include <vector> #include <iostream> using namespace std; int main() { int n; cin >> n; vector<int> d; d.push_back(1); for (int i = 2; i <= n; ++i) { for (auto it = d.begin(); it != d.end(); ++it) *it *= i; for (size_t j = 0; j < d.size(); ++j) { if (d[j] < 10) continue; if (j == d.size() - 1) d.push_back(0); d[j + 1] += d[j] / 10; d[j] %= 10; } } for (auto it = d.rbegin(); it != d.rend(); ++it) cout << *it; return 0; }
Octowl + 0 comments I thought this would be a cake walk. Just implement a tail recursive function and call it on N.
...then I realized I was trying to do this in JavaScript.
My function is fine. It works. The answers are right.
BUT THE TESTS FAIL because JS has precision limits and returns answers in Scientific Notation!
whuang + 0 comments For those of you interested in challenging yourself to write this in C
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int main(){ int n, length_digit = 1; scanf("%d",&n); int *r = malloc(60 * sizeof(int)); r[0] = 1; for (int factor = 2; factor <= n; factor++) { int *carry = malloc( (length_digit + 2) * sizeof(int)); // first, evaluate product for (int i = 0; i < length_digit; i++) { r[i] *= factor; r[i] += carry[i]; if (r[i] / 100 > 0) { carry[i + 2] += r[i] / 100; carry[i + 1] += (r[i] % 100) / 10; r[i] = r[i] % 10; } else if (r[i] / 10 > 0) { carry[i + 1] += r[i] / 10; r[i] = r[i] % 10; } } // second, consider if length of digit increases if (carry[length_digit + 1] > 0) { r[length_digit + 1] = carry[length_digit + 1]; r[length_digit + 1] += carry[length_digit] / 10; r[length_digit] = carry[length_digit] % 10; length_digit += 2; } else if (carry[length_digit] > 0) { r[length_digit] = carry[length_digit]; length_digit++; } } // print for(int i = length_digit - 1; i >= 0; i--){ printf("%d", r[i]); } }
GabeKagan + 0 comments This is hilariously trivial in Ruby, which automatically creates big integers (Bignum) as needed. I should probably try it in a language that doesn't one of these days.
Load more conversations
Sort 838 Discussions, By:
Please Login in order to post a comment