fork download
  1. %{
  2. #include <stdio.h>
  3. #include <math.h>
  4. #include <stdbool.h>
  5. double num1, num2;
  6. int operation = 0;
  7. int gcd(int a, int b) {
  8. if (b == 0) return a;
  9. return gcd(b, a % b);
  10. }
  11. void factors(int n) {
  12. printf("Factors of %d: ", n);
  13. for (int i = 1; i <= n; i++) {
  14. if (n % i == 0) {
  15. printf("%d ", i);
  16. }
  17. }
  18. printf("\n");
  19. }
  20. bool are_coprime(int a, int b) {
  21. return gcd(a, b) == 1;
  22. }
  23. %}
  24. %%
  25. "exponent"|"exp"|"^" { operation = 1; }
  26. "sqrt"|"square root" { operation = 2; }
  27. "cbrt"|"cube root" { operation = 3; }
  28. "factors" { operation = 4; }
  29. "coprime" { operation = 5; }
  30. [0-9]+(\.[0-9]+)? {
  31. if (operation == 0) num1 = atof(yytext);
  32. else num2 = atof(yytext);
  33. }
  34. \n {
  35. switch(operation) {
  36. case 1:
  37. printf("%.2f^%.2f = %.2f\n", num1, num2, pow(num1, num2));
  38. break;
  39. case 2:
  40. printf("sqrt(%.2f) = %.2f\n", num1, sqrt(num1));
  41. break;
  42. case 3:
  43. printf("cbrt(%.2f) = %.2f\n", num1, cbrt(num1));
  44. break;
  45. case 4:
  46. factors((int)num1);
  47. break;
  48. case 5:
  49. printf("%d and %d are %scoprime\n", (int)num1, (int)num2,
  50. are_coprime((int)num1, (int)num2) ? "" : "not ");
  51. break;
  52. default:
  53. printf("Invalid operation\n");
  54. }
  55. operation = 0;
  56. }
  57. [ \t]+ ; // Ignore whitespace
  58. . { printf("Invalid input\n"); }
  59. %%
  60. int main() {
  61. printf("Enter calculations (e.g. '2 exponent 3' or '16 sqrt'):\n");
  62. yylex();
  63. return 0;
  64. }
  65. int yywrap() {
  66. return 1;
  67. }
Success #stdin #stdout #stderr 0.03s 6952KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
ERROR: /home/2rGvce/prog:2:1: Syntax error: Operator expected
ERROR: /home/2rGvce/prog:67:0: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit