Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. #include <unistd.h>
  2. #include <stdio.h>
  3.  
  4. void ft_putstr(char *str)
  5. {
  6. int i;
  7.  
  8. i = 0;
  9. while (str[i])
  10. {
  11. write(1,&str[i],1);
  12. i++;
  13. }
  14. }
  15.  
  16. int ft_atoi(char *str)
  17. {
  18. int i;
  19. int is_neg;
  20. int res;
  21.  
  22. i = 0;
  23. is_neg = 0;
  24. res = 0;
  25. if (!str)
  26. return (0);
  27. while (str[i] == '\t' || str[i] == '\n' || str[i] == '\r' || str[i] == '\v' || str[i] == '\f')
  28. i++;
  29. if (str[i] == '+' || str[i] == '-')
  30. {
  31. if (str[i] == '-')
  32. is_neg = 1;
  33. i++;
  34. }
  35. while (str[i] >= '0' && str[i] <= '9')
  36. {
  37. res = (res * 10) + (str[i] - '0');
  38. i++;
  39. }
  40. return (is_neg ? -res : res);
  41. }
  42.  
  43. void ft_putnbr(int nb)
  44. {
  45. char c;
  46.  
  47. if (nb == -2147483648)
  48. ft_putstr("-2147483648");
  49. if (nb < 0)
  50. {
  51. nb = -nb;
  52. write(1, "-", 1);
  53. }
  54. if (nb < 10)
  55. {
  56. c = nb + '0';
  57. write(1, &c, 1);
  58. }
  59. else
  60. {
  61. ft_putnbr(nb / 10);
  62. ft_putnbr(nb % 10);
  63. }
  64. }
  65.  
  66. int is_prime(int nb)
  67. {
  68. int i;
  69.  
  70. i = 2;
  71. if (nb < 0)
  72. return (0);
  73. while (i <= (nb / 2))
  74. {
  75. if (!(nb % i))
  76. return (0);
  77. else
  78. i++;
  79. }
  80. return (1);
  81. }
  82.  
  83. int main(int ac, char *av[])
  84. {
  85. int sum;
  86. int nb;
  87.  
  88. sum = 0;
  89. nb = ft_atoi(av[1]);
  90. if (ac == 2 && nb > 0)
  91. {
  92. while (nb > 0)
  93. {
  94. if (is_prime(nb))
  95. sum += nb;
  96. nb--;
  97. }
  98. ft_putnbr(sum);
  99. }
  100. else
  101. write (1,"0",1);
  102. write(1, "\n", 1);
  103. return (0);
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement