fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. typedef struct ans{
  5. int factor;
  6. int squared;
  7. bool imaginary;
  8. } ans;
  9.  
  10. ans mysqrt(int);
  11. void output(ans);
  12.  
  13. int main(void){
  14. output(mysqrt(171));
  15. printf("\n");
  16. output(mysqrt(0));
  17. printf("\n");
  18.  
  19. output(mysqrt(500));
  20. printf("\n");
  21.  
  22. output(mysqrt(1));
  23. printf("\n");
  24.  
  25. output(mysqrt(-171));
  26. printf("\n");
  27.  
  28. output(mysqrt(-500));
  29. printf("\n");
  30.  
  31.  
  32. /*
  33. this outputs
  34. 1 * i
  35. not
  36. i
  37. but this is by design.
  38. */
  39. output(mysqrt(-1));
  40. printf("\n");
  41.  
  42. }
  43.  
  44. ans mysqrt(int x){
  45. int val;
  46. ans ret;
  47.  
  48.  
  49. if(x < 0){
  50. ret.imaginary = true;
  51. val = -x;
  52.  
  53. }else{
  54. ret.imaginary = false;
  55. val = x;
  56. }
  57.  
  58.  
  59. if(val == 0){
  60. ret.factor = 0;
  61. ret.squared = 1;
  62. return ret;
  63. }
  64.  
  65. ret.factor = 1;
  66. for(int i = 2;;i++){
  67. int square = i * i;
  68. if(square > val){
  69. break;
  70. }
  71. while(true){
  72. if( val % square != 0){
  73. break;
  74. }
  75. val /= square ;
  76. ret.factor *= i;
  77. continue;
  78. }
  79. }
  80. ret.squared = val;
  81. return ret;
  82. }
  83.  
  84. void output(ans x){
  85. if(x.squared == 1){
  86. printf("%d",x.factor);
  87. }else{
  88. printf("%d * sqrt(%d)",x.factor,x.squared);
  89. }
  90. if(x.imaginary == true){
  91. printf(" * i");
  92.  
  93. }
  94. }
  95.  
  96.  
Success #stdin #stdout 0.02s 1720KB
stdin
Standard input is empty
stdout
3 * sqrt(19)
0
10 * sqrt(5)
1
3 * sqrt(19) * i
10 * sqrt(5) * i
1 * i