%{
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
double num1, num2;
int operation = 0;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
void factors(int n) {
printf("Factors of %d: ", n);
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
printf("%d ", i);
}
}
printf("\n");
}
bool are_coprime(int a, int b) {
return gcd(a, b) == 1;
}
%}
%%
"exponent"|"exp"|"^" { operation = 1; }
"sqrt"|"square root" { operation = 2; }
"cbrt"|"cube root" { operation = 3; }
"factors" { operation = 4; }
"coprime" { operation = 5; }
[0-9]+(\.[0-9]+)? {
if (operation == 0) num1 = atof(yytext);
else num2 = atof(yytext);
}
\n {
switch(operation) {
case 1:
printf("%.2f^%.2f = %.2f\n", num1, num2, pow(num1, num2));
break;
case 2:
printf
("
sqrt(%.2f) = %.2f\n", num1, sqrt(num1));break;
case 3:
printf("cbrt(%.2f) = %.2f\n", num1, cbrt(num1));
break;
case 4:
factors((int)num1);
break;
case 5:
printf("%d and %d are %scoprime\n", (int)num1, (int)num2,
are_coprime((int)num1, (int)num2) ? "" : "not ");
break;
default:
printf("Invalid operation\n");
}
operation = 0;
}
[ \t]+ ; // Ignore whitespace
. { printf("Invalid input\n"); }
%%
int main() {
printf("Enter calculations (e.g. '2 exponent 3' or '16 sqrt'):\n");
yylex();
return 0;
}
int yywrap() {
return 1;
}
JXsKI2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxtYXRoLmg+CiNpbmNsdWRlIDxzdGRib29sLmg+CmRvdWJsZSBudW0xLCBudW0yOwppbnQgb3BlcmF0aW9uID0gMDsKaW50IGdjZChpbnQgYSwgaW50IGIpIHsKaWYgKGIgPT0gMCkgcmV0dXJuIGE7CnJldHVybiBnY2QoYiwgYSAlIGIpOwp9CnZvaWQgZmFjdG9ycyhpbnQgbikgewpwcmludGYoIkZhY3RvcnMgb2YgJWQ6ICIsIG4pOwpmb3IgKGludCBpID0gMTsgaSA8PSBuOyBpKyspIHsKaWYgK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