math.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* Copyright (C) 2016 Jeremiah Orians
  2. * This file is part of M2-Planet.
  3. *
  4. * M2-Planet is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * M2-Planet is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with M2-Planet. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include<stdlib.h>
  18. #include<stdio.h>
  19. #include<string.h>
  20. char* numerate_number(int a)
  21. {
  22. char* result = malloc(16);
  23. memset(result, 0, 16);
  24. int i = 0;
  25. /* Deal with Zero case */
  26. if(0 == a)
  27. {
  28. result[0] = '0';
  29. result[1] = 10;
  30. return result;
  31. }
  32. /* Deal with negatives */
  33. if(0 > a)
  34. {
  35. result[0] = '-';
  36. i = 1;
  37. a = a * -1;
  38. }
  39. /* Using the largest 10^n number possible in 32bits */
  40. int divisor = 0x3B9ACA00;
  41. /* Skip leading Zeros */
  42. while(0 == (a / divisor)) divisor = divisor / 10;
  43. /* Now simply collect numbers until divisor is gone */
  44. while(0 < divisor)
  45. {
  46. result[i] = ((a / divisor) + 48);
  47. a = a % divisor;
  48. divisor = divisor / 10;
  49. i = i + 1;
  50. }
  51. result[i] = 10;
  52. return result;
  53. }
  54. void write_string(char* s, FILE* f)
  55. {
  56. while(0 != s[0])
  57. {
  58. fputc(s[0], f);
  59. s = s + 1;
  60. }
  61. }
  62. int main()
  63. {
  64. write_string(numerate_number(1248), stdout);
  65. write_string(numerate_number(0), stdout);
  66. write_string(numerate_number(-1248), stdout);
  67. return 0;
  68. }