-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1668 lines (1420 loc) · 62.2 KB
/
Program.cs
File metadata and controls
1668 lines (1420 loc) · 62.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Globalization;
using System.Numerics; // For BigInteger support in factorials > 20
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Linq;
class Calculator
{
static string version = "1.5.0 (Stable)";
static void Main()
{
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
while (true)
{
Console.Clear();
PrintMenu();
Console.Write("Enter operator: ");
string? input = Console.ReadLine();
string op = input?.Trim().ToUpper() ?? "";
if (op == "EXIT")
{
Console.WriteLine("\nThank you for using the calculator!");
Console.ResetColor();
Console.Clear();
break;
}
if (op == "HELP" || op == "")
{
ShowHelp();
continue;
}
try
{
switch (op)
{
case "ADD": Add(); break;
case "SUB": Subtract(); break;
case "MULTIPLY": Multiply(); break;
case "DIVIDE": Divide(); break;
case "ROOT": Root(); break;
case "SQUAREROOT": SquareRoot(); break;
case "CUBEROOT": CubeRoot(); break;
case "EXPONENT": Exponent(); break;
case "MULTI-OPERATION": MultiOperation(); break;
case "SQUARE": Square(); break;
case "CUBE": Cube(); break;
case "FACTORIAL": Factorial(); break;
case "TETRATION": Tetration(); break; //Advanced Operation
case "PENTATION": Pentation(); break; //Advanced Operation
case "TEST": RunTestSuite(); break; // Hidden option for testing
case "PI": ShowSecretPi(); break; // Hidden Easter Egg for Pi
case "PHI": ShowGoldenRatio(); break;// Hidden Easter Egg for Golden Ratio
case "EULER": ShowEuler(); break;// Hidden Easter Egg for Euler's Number
case "CREDITS": ShowCredits(); break;// Hidden Credits Page
case "SHOW-ROSTER-SET": ShowRosterSet(); break; // Hidden Easter Egg for Roster Set
case "VERSION": ShowVersion(); break; // Hidden Easter Egg for Version Info
case "SELF-DESTRUCT": InitiateSelfDestruct(); break; // Hidden Easter Egg for Self-Destruct Sequence
// NEW THEME LOGIC
case string s when s.Contains("THEME"):
// 1. Display the Usage first as requested
Console.WriteLine("\nUsage: THEME [OPTION]");
Console.WriteLine("Options: MATRIX, CYBER, BLOOD, CLASSIC");
// 2. Ask the user for the input
Console.Write("\nWhich theme would you like to apply? ");
string themeChoice = (Console.ReadLine() ?? "").Trim().ToUpper();
// 3. Call the method
SetTheme(themeChoice);
break;
default:
Console.WriteLine("\nInvalid! Check spelling. Press Enter...");
Console.ReadLine();
break;
}
}
catch (Exception ex)
{
Console.WriteLine($"\nError: {ex.Message}\nPress Enter...");
Console.ReadLine();
}
}
}
static void PrintMenu()
{
Console.WriteLine("=== ADVANCED CALCULATOR ===");
Console.WriteLine("\nAvailable Operations:");
Console.WriteLine(" ADD, SUB, MULTIPLY, DIVIDE, ROOT, SQUAREROOT, CUBEROOT, EXPONENT, MULTI-OPERATION, SQUARE, CUBE, FACTORIAL, TETRATION, PENTATION, SET-THEME");
Console.WriteLine("\n Type HELP for examples or EXIT to quit");
Console.WriteLine(new string('=', 50));
}
static void ShowHelp()
{
Console.Clear();
Console.WriteLine("=== HELP & EXAMPLES ===");
Console.WriteLine(" ADD - Addition");
Console.WriteLine(" SUB - Subtraction");
Console.WriteLine(" MULTIPLY - Multiplication");
Console.WriteLine(" DIVIDE - Division");
Console.WriteLine(" ROOT - Nth Root");
Console.WriteLine(" SQUAREROOT - Square Root (√16)");
Console.WriteLine(" CUBEROOT - Cube Root (∛8)");
Console.WriteLine(" EXPONENT - Power (2^3)");
Console.WriteLine(" MULTI-OPERATION - Basic math (2+3, 5*4)");
Console.WriteLine(" SQUARE - Squares any number (2²)");
Console.WriteLine(" CUBE - Cubes any number (2³)");
Console.WriteLine(" FACTORIAL - Finds the factorial of a number (n!)");
Console.WriteLine(" TETRATION - Tetration (n^n^n...) or iterated exponentiation (²3)");
Console.WriteLine(" PENTATION - Pentation (n^n^n^n...) or iterated tetration (₂2)");
Console.WriteLine(" SET-THEME - Change the color scheme of the calculator, apply a fun theme! or set a particular vibe or theme for your calculations.");
Console.WriteLine("\nPress Enter to return...");
Console.ReadLine();
}
static void MultiOperation()
{
Console.Clear();
Console.WriteLine("=== INFINITY BREAKER: MULTI-OP ENGINE (BEDMAS) ===");
Console.WriteLine("Supports: +, -, *, /, ^ (Power), and ( ) Brackets");
Console.Write("\nEnter expression: ");
string? expr = Console.ReadLine();
if (string.IsNullOrWhiteSpace(expr)) return;
try
{
// The Engine call: maintains 500-digit precision
string result = Evaluate(expr.Trim());
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n--------------------------------------------------");
Console.WriteLine($"RESULT: {result}");
Console.WriteLine("--------------------------------------------------");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"\n[ ENGINE ERROR ]: {ex.Message}");
Console.ResetColor();
}
Console.WriteLine("\nPress Enter to return to main menu...");
Console.ReadLine();
}
static string Evaluate(string expression)
{
expression = expression.Replace(" ", "").Replace("**", "^");
// Regex splits numbers while keeping operators and brackets
string[] tokens = System.Text.RegularExpressions.Regex.Split(expression, @"([\+\-\*\/\^\(\)])");
var values = new Stack<string>(); // Storing numbers as strings to keep precision
var ops = new Stack<char>();
for (int i = 0; i < tokens.Length; i++)
{
string token = tokens[i];
if (string.IsNullOrEmpty(token)) continue;
// If it's a number (including decimals), push as string
if (char.IsDigit(token[0]) || (token.Length > 1 && token[0] == '-'))
{
values.Push(token);
}
else if (token == "(") { ops.Push('('); }
else if (token == ")")
{
while (ops.Count > 0 && ops.Peek() != '(')
values.Push(ApplyBigOp(ops.Pop(), values.Pop(), values.Pop()));
ops.Pop();
}
else if ("+-*/^".Contains(token))
{
char op = token[0];
while (ops.Count > 0 && ops.Peek() != '(' && HasPrecedence(op, ops.Peek()))
values.Push(ApplyBigOp(ops.Pop(), values.Pop(), values.Pop()));
ops.Push(op);
}
}
while (ops.Count > 0)
values.Push(ApplyBigOp(ops.Pop(), values.Pop(), values.Pop()));
return values.Pop();
}
static bool HasPrecedence(char op1, char op2)
{
// Higher number = higher priority
static int GetPriority(char op) => op switch {
'^' => 3,
'*' or '/' => 2,
'+' or '-' => 1,
_ => 0
};
// If op2 is higher or equal priority, it must be calculated first
return GetPriority(op2) >= GetPriority(op1);
}
static string ApplyBigOp(char op, string s2, string s1)
{
// 1. Alignment and Parsing
int dot1 = s1.IndexOf('.');
int dot2 = s2.IndexOf('.');
int p1 = dot1 < 0 ? 0 : s1.Length - dot1 - 1;
int p2 = dot2 < 0 ? 0 : s2.Length - dot2 - 1;
// 2. Perform Math based on operation type
BigInteger n1, n2, res = 0;
int finalP = 0;
switch (op)
{
case '+':
case '-':
finalP = Math.Max(p1, p2);
n1 = BigInteger.Parse(s1.Replace(".", "") + new string('0', finalP - p1));
n2 = BigInteger.Parse(s2.Replace(".", "") + new string('0', finalP - p2));
res = (op == '+') ? n1 + n2 : n1 - n2;
break;
case '*':
finalP = p1 + p2;
n1 = BigInteger.Parse(s1.Replace(".", ""));
n2 = BigInteger.Parse(s2.Replace(".", ""));
res = n1 * n2;
break;
case '/':
n1 = BigInteger.Parse(s1.Replace(".", ""));
n2 = BigInteger.Parse(s2.Replace(".", ""));
if (n2 == 0) throw new DivideByZeroException();
// Scale up for 500-place division
n1 *= BigInteger.Pow(10, 500 + p2 - p1);
res = n1 / n2;
finalP = 500;
break;
case '^':
// Simple power logic for whole number exponents
n1 = BigInteger.Parse(s1.Replace(".", ""));
int exponent = int.Parse(s2);
res = BigInteger.Pow(n1, exponent);
finalP = p1 * exponent;
break;
}
// 3. Format back to string to pass to the next BEDMAS step
string r = res.ToString();
bool neg = r.StartsWith("-");
if (neg) r = r.Substring(1);
if (r.Length <= finalP) r = r.PadLeft(finalP + 1, '0');
string result = (neg ? "-" : "") + r.Insert(r.Length - finalP, ".");
// Cap at 500 decimals for internal steps
int dotIdx = result.IndexOf('.');
if (dotIdx != -1 && (result.Length - dotIdx - 1) > 500)
result = result.Substring(0, dotIdx + 501);
return result.TrimEnd('0').TrimEnd('.');
}
static void Add()
{
BigDecBinaryOp("ADD", (a, b) => a + b);
Console.WriteLine("\nPress Enter to return...");
Console.ReadLine();
}
static void Subtract()
{
BigDecBinaryOp("SUB", (a, b) => a - b);
Console.WriteLine("\nPress Enter to return...");
Console.ReadLine();
}
static void Multiply()
{
Console.WriteLine("\n--- MULTIPLICATION MODE (500 Decimal Limit) ---");
Console.Write("Enter first number: ");
string s1 = (Console.ReadLine() ?? "0").Trim();
Console.Write("Enter second number: ");
string s2 = (Console.ReadLine() ?? "0").Trim();
// 1. Count decimal places for both
int dot1 = s1.IndexOf('.');
int dot2 = s2.IndexOf('.');
int places1 = dot1 < 0 ? 0 : s1.Length - dot1 - 1;
int places2 = dot2 < 0 ? 0 : s2.Length - dot2 - 1;
// Total places in the result is the sum of input places
int totalDecimalPlaces = places1 + places2;
// 2. Remove dots and multiply as pure integers
string clean1 = s1.Replace(".", "");
string clean2 = s2.Replace(".", "");
if (BigInteger.TryParse(clean1, out BigInteger n1) && BigInteger.TryParse(clean2, out BigInteger n2))
{
// The CPU will crush this even if n1/n2 have 1000+ digits
BigInteger result = n1 * n2;
string resStr = result.ToString();
bool isNegative = resStr.StartsWith("-");
if (isNegative) resStr = resStr.Substring(1);
// 3. Re-insert the decimal point at totalDecimalPlaces
if (resStr.Length <= totalDecimalPlaces)
{
resStr = resStr.PadLeft(totalDecimalPlaces + 1, '0');
}
int dotPos = resStr.Length - totalDecimalPlaces;
string finalResult = (isNegative ? "-" : "") + resStr.Insert(dotPos, ".");
// 4. APPLY THE 500-PLACE CAP
int finalDotPos = finalResult.IndexOf('.');
if (finalDotPos != -1)
{
int currentDecs = finalResult.Length - finalDotPos - 1;
if (currentDecs > 500)
{
finalResult = finalResult.Substring(0, finalDotPos + 501);
}
}
// 5. Final Cleanup
finalResult = finalResult.TrimEnd('0').TrimEnd('.');
if (string.IsNullOrEmpty(finalResult) || finalResult == "-") finalResult = "0";
Console.WriteLine("--------------------------------------------------");
if (finalResult.Length > 80)
Console.WriteLine($"Result: {finalResult.Substring(0, 40)}... [Total Length: {finalResult.Length}]");
else
Console.WriteLine($"Result: {finalResult}");
Console.WriteLine("--------------------------------------------------");
}
else
{
Console.WriteLine("Invalid input.");
}
Console.ReadLine();
}
static void Divide()
{
Console.WriteLine("\n--- DIVISION MODE (500 Decimal Places) ---");
// 1. Get Inputs
Console.Write("Enter Dividend (Numerator): ");
string s1 = (Console.ReadLine() ?? "0").Trim();
Console.Write("Enter Divisor (Denominator): ");
string s2 = (Console.ReadLine() ?? "0").Trim();
// 2. Extract whole numbers and track their existing decimal points
int dot1 = s1.IndexOf('.');
int dot2 = s2.IndexOf('.');
int places1 = dot1 < 0 ? 0 : s1.Length - dot1 - 1;
int places2 = dot2 < 0 ? 0 : s2.Length - dot2 - 1;
// Convert to BigIntegers (stripping the dots)
if (BigInteger.TryParse(s1.Replace(".", ""), out BigInteger n1) &&
BigInteger.TryParse(s2.Replace(".", ""), out BigInteger n2))
{
if (n2 == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("\n[ MATH ERROR ]: Division by zero is undefined.");
Console.WriteLine("The universe remains intact, but this calculation cannot proceed.");
Console.ResetColor();
Console.WriteLine("\nPress Enter to return to the menu...");
Console.ReadLine();
return; // This exits the Divide() method safely
}
// 3. THE SCALING TRICK:
// We add 500 zeros to the numerator to "force" 500 decimal places.
// We also adjust for the decimal places that were already there.
int precision = 500;
BigInteger scaledN1 = n1 * BigInteger.Pow(10, precision + places2 - places1);
Console.WriteLine("Dividing... (Precision: 500 decimal places)");
// The actual math happens here:
BigInteger quotient = scaledN1 / n2;
// 4. Formatting the string back to a decimal
string resStr = quotient.ToString();
bool isNegative = resStr.StartsWith("-");
if (isNegative) resStr = resStr.Substring(1);
// Ensure we have enough length to place the dot
if (resStr.Length <= precision)
resStr = resStr.PadLeft(precision + 1, '0');
int dotPos = resStr.Length - precision;
string finalResult = (isNegative ? "-" : "") + resStr.Insert(dotPos, ".");
// 5. Cleanup: Remove trailing zeros for a professional look
finalResult = finalResult.TrimEnd('0').TrimEnd('.');
if (string.IsNullOrEmpty(finalResult) || finalResult == "-") finalResult = "0";
Console.WriteLine("--------------------------------------------------");
if (finalResult.Length > 80)
Console.WriteLine($"Result: {finalResult.Substring(0, 40)}... [Total Chars: {finalResult.Length}]");
else
Console.WriteLine($"Result: {finalResult}");
Console.WriteLine("--------------------------------------------------");
}
else
{
Console.WriteLine("Invalid input. Please enter valid numbers.");
}
Console.WriteLine("\nPress Enter to return...");
Console.ReadLine();
}
static void Root()
{
Console.WriteLine("\n--- Nth ROOT MODE (High Precision & Imaginary Support) ---");
// 1. Get Inputs
Console.Write("Enter the number: ");
string inputA = Console.ReadLine() ?? "";
Console.Write("Enter the root degree (e.g., 5 for Root 5): ");
string inputN = Console.ReadLine() ?? "";
if (!BigInteger.TryParse(inputA, out BigInteger A) || !int.TryParse(inputN, out int n) || n <= 0)
{
Console.WriteLine("Invalid input. Root degree must be a positive integer.");
return;
}
// 2. Determine if the result is Imaginary
// Even roots (2, 4, 6...) of negative numbers require 'i'
bool isImaginary = (A < 0 && n % 2 == 0);
// 3. Set Precision (500 decimal places)
int precision = 500;
// We calculate using the Absolute Value (positive version)
BigInteger absA = BigInteger.Abs(A);
// Scaling Trick: A * 10^(precision * n)
BigInteger multiplier = BigInteger.Pow(10, precision * n);
BigInteger scaledNumber = absA * multiplier;
Console.WriteLine($"\nCalculating... {(isImaginary ? "(Imaginary Result)" : "")}");
// 4. The Math (Newton-Raphson)
BigInteger rootValue = BigIntNthRoot(scaledNumber, n);
// 5. Formatting the result
string rootStr = rootValue.ToString();
// Pad with leading zeros if the result is a tiny decimal
if (rootStr.Length <= precision)
rootStr = rootStr.PadLeft(precision + 1, '0');
int dotPosition = rootStr.Length - precision;
string integerPart = rootStr.Substring(0, dotPosition);
string decimalPart = rootStr.Substring(dotPosition);
// Apply negative sign for odd roots of negative numbers
if (A < 0 && n % 2 != 0)
{
integerPart = "-" + integerPart;
}
// 6. Display Result
Console.WriteLine("--------------------------------------------------");
string suffix = isImaginary ? " i" : "";
if (integerPart.Length > 25)
{
// Scientific notation for massive whole numbers
Console.WriteLine($"Result: {integerPart[0]}.{integerPart.Substring(1, 10)}... x 10^{integerPart.Replace("-","").Length - 1}{suffix}");
}
else
{
// Standard view for smaller whole numbers
Console.WriteLine($"Result: {integerPart}.{decimalPart.Substring(0, 50)}...{suffix}");
}
Console.WriteLine($"\nDONE! Calculated to {precision} decimal places.");
if (isImaginary)
Console.WriteLine("Status: 🧬 Imaginary/Complex Number identified.");
else if (integerPart.Replace("-","").Length > 308)
Console.WriteLine("Status: 🚀 Infinity Root broken!");
Console.WriteLine("--------------------------------------------------");
// 7. Save Option
Console.Write("Save all 500 decimal places to file? (y/n): ");
if (Console.ReadLine()?.ToLower() == "y")
{
File.WriteAllText("root_result.txt", $"{integerPart}.{decimalPart}{suffix}");
Console.WriteLine("Saved to 'root_result.txt'.");
}
Console.WriteLine("\nPress Enter to return...");
Console.ReadLine();
}
// Essential Helper Function (Newton-Raphson)
static BigInteger BigIntNthRoot(BigInteger A, int n)
{
if (A == 0) return 0;
if (n == 1) return A;
BigInteger x = A / n; // Starting guess
if (x < 1) x = 1;
BigInteger lastX;
//BigInteger nMinus1 = n - 1;
int nMinus1 = n - 1; // Using int for n-1 since n is an int
do
{
lastX = x;
// The Formula: x = ((n-1)x + A / x^(n-1)) / n
BigInteger xToNMinus1 = BigInteger.Pow(x, nMinus1);
x = ((nMinus1 * x) + (A / xToNMinus1)) / n;
} while (BigInteger.Abs(x - lastX) > 1);
return x;
}
static void SquareRoot()
{
Console.WriteLine("\n--- SQUARE ROOT MODE (High Precision & Imaginary Support) ---");
// 1. Get Input
Console.Write("Enter a number: ");
string input = Console.ReadLine() ?? "";
if (!BigInteger.TryParse(input, out BigInteger number))
{
Console.WriteLine("Invalid input.");
return;
}
// NEW: Check if the number is negative to handle 'i'
bool isImaginary = number < 0;
BigInteger absNumber = BigInteger.Abs(number);
// 2. Set Precision
int precision = 500;
// Scaling Trick: We use the absolute value for the actual calculation
BigInteger multiplier = BigInteger.Pow(10, precision * 2);
BigInteger scaledNumber = absNumber * multiplier;
Console.WriteLine($"\nCalculating root to {precision} decimal places... {(isImaginary ? "(Imaginary Result)" : "")}");
// 3. The Math (Using Newton's Method)
BigInteger root = BigIntSquareRoot(scaledNumber);
// 4. Format the result string
string rootStr = root.ToString();
if (rootStr.Length <= precision)
{
rootStr = rootStr.PadLeft(precision + 1, '0');
}
int dotPosition = rootStr.Length - precision;
string integerPart = rootStr.Substring(0, dotPosition);
string decimalPart = rootStr.Substring(dotPosition);
// 5. Display Result
Console.WriteLine("--------------------------------------------------");
// Add 'i' suffix if the input was negative
string suffix = isImaginary ? " i" : "";
if (integerPart.Length > 20)
{
Console.WriteLine($"Root: {integerPart[0]}.{integerPart.Substring(1, 5)}... x 10^{integerPart.Length - 1}{suffix}");
}
else
{
// Show first 50 decimals for clarity
Console.WriteLine($"Root: {integerPart}.{decimalPart.Substring(0, 50)}...{suffix}");
}
Console.WriteLine($"\nDONE! Calculated to {precision} decimal places.");
if (isImaginary)
Console.WriteLine("Status: 🧬 Imaginary result handled.");
else if (integerPart.Length > 308)
Console.WriteLine("Status: 🚀 Infinity Root broken!");
Console.WriteLine("--------------------------------------------------");
// 6. Save to File
Console.Write("Save full precision result to text file? (y/n): ");
if (Console.ReadLine()?.ToLower() == "y")
{
File.WriteAllText("sqrt_result.txt", $"{integerPart}.{decimalPart}{suffix}");
Console.WriteLine("Saved to 'sqrt_result.txt'.");
}
Console.WriteLine("\nPress Enter...");
Console.ReadLine();
}
static void CubeRoot()
{
Console.WriteLine("\n--- CUBE ROOT MODE (High Precision) ---");
// 1. Get Input
Console.Write("Enter a number: ");
string input = Console.ReadLine() ?? "";
if (!BigInteger.TryParse(input, out BigInteger number))
{
Console.WriteLine("Invalid input.");
return;
}
bool isInputNegative = number < 0;
int precision = 500;
// 2. The Choice (Only for Negative Numbers)
string mode = "R"; // Default to Real
if (isInputNegative)
{
Console.WriteLine("\nNegative detected! Choose output type:");
Console.WriteLine("[R] Real Root (Negative number)");
Console.WriteLine("[C] Complex Root (Principal root involving 'i')");
Console.Write("Selection: ");
mode = Console.ReadLine()?.ToUpper() ?? "R";
}
// 3. Scaling & Calculation
BigInteger absNumber = BigInteger.Abs(number);
BigInteger multiplier = BigInteger.Pow(10, precision * 3);
BigInteger scaledNumber = absNumber * multiplier;
Console.WriteLine($"\nCalculating... (Precision: {precision} places)");
BigInteger rootMagnitude = BigIntCubeRoot(scaledNumber);
// 4. Formatting Magnitude
string rootStr = rootMagnitude.ToString().PadLeft(precision + 1, '0');
int dotPos = rootStr.Length - precision;
string magInt = rootStr.Substring(0, dotPos);
string magDec = rootStr.Substring(dotPos);
// 5. Logical Branching for Display
Console.WriteLine("--------------------------------------------------");
if (mode == "C" && isInputNegative)
{
// Complex Root Math: (root/2) + (root * sin(60°))i
// Sin(60°) is approx 0.866025
BigInteger halfRoot = rootMagnitude / 2;
string hStr = halfRoot.ToString().PadLeft(precision + 1, '0');
string hInt = hStr.Substring(0, hStr.Length - precision);
string hDec = hStr.Substring(hStr.Length - precision);
Console.WriteLine("MODE: COMPLEX PRINCIPAL ROOT");
Console.WriteLine($"Result: {hInt}.{hDec.Substring(0, 50)}... + ({magInt}.{magDec.Substring(0, 10)}... * 0.866)i");
}
else
{
// Standard Real Root
string prefix = isInputNegative ? "-" : "";
Console.WriteLine("MODE: REAL ROOT");
Console.WriteLine($"Result: {prefix}{magInt}.{magDec.Substring(0, 50)}...");
}
Console.WriteLine("--------------------------------------------------");
// 6. Save
Console.Write("Save full 500-digit result to file? (y/n): ");
if (Console.ReadLine()?.ToLower() == "y")
{
string finalOut = (mode == "C" && isInputNegative) ? "Complex values saved in 'cubert_complex.txt'" : $"{magInt}.{magDec}";
File.WriteAllText("cubert_result.txt", finalOut);
}
Console.WriteLine("\nPress Enter...");
Console.ReadLine();
}
static BigInteger BigIntCubeRoot(BigInteger n)
{
if (n == 0) return 0;
// Handle negatives for cube roots
BigInteger absN = BigInteger.Abs(n);
// Initial guess
BigInteger x = absN >> (absN.ToByteArray().Length * 2);
if (x < 1) x = absN;
BigInteger lastX;
do
{
lastX = x;
// Newton's Method for Cube Root: x = (2x + n/x^2) / 3
x = (2 * x + (absN / (x * x))) / 3;
} while (BigInteger.Abs(x - lastX) > 1);
return n < 0 ? -x : x;
}
static void Exponent()
{
Console.WriteLine("\n--- EXPONENT MODE (Positive Whole Numbers) ---");
// 1. Get Inputs
int b = GetInt("BASE");
int e = GetInt("EXPONENT");
// Strictly positive logic as requested
if (b < 0 || e < 0)
{
Console.WriteLine("Error: This mode is optimized for positive whole numbers.");
return;
}
// 2. Predict the scale
double predictedDigits = (e * Math.Log10(b)) + 1;
// Handle b=1 separately because Log10(1) is 0
if (b == 1) predictedDigits = 1;
int predictedCount = (int)Math.Floor(predictedDigits);
Console.WriteLine($"\nPrediction: This result will have approx. {predictedCount:N0} digits.");
// 3. Safety Check for 4GB RAM
if (predictedCount > 1000000)
{
Console.WriteLine("🚨 WARNING: Result exceeds 1,000,000 digits.");
Console.WriteLine("Calculation is easy, but displaying it may lag your PC.");
Console.Write("Proceed anyway? (y/n): ");
if (Console.ReadLine()?.ToLower() != "y") return;
}
// 4. Perform Calculation
Console.WriteLine("Calculating...");
BigInteger result = BigInteger.Pow(b, e);
// 5. Formatting
string fullResult = result.ToString();
int actualDigits = fullResult.Length;
// 6. Display Logic
Console.Write("How would you like to see the result?\n[S] Shortened or [D] All Digits? (s/d): ");
string mode = Console.ReadLine()?.ToLower() ?? "s";
Console.WriteLine("--------------------------------------------------");
if (mode == "s" && actualDigits > 20)
{
// Scientific Notation: 1.2345... x 10^Length
Console.WriteLine($"Result: {fullResult[0]}.{fullResult.Substring(1, 10)}... x 10^{actualDigits - 1}");
}
else
{
Console.WriteLine($"Result: {fullResult}");
}
// 7. Status Report
Console.WriteLine($"\nDONE! Total Digits: {actualDigits:N0}");
if (actualDigits > 308)
Console.WriteLine("Status: 🚀 Infinity Broken successfully!");
else
Console.WriteLine("Status: ✅ Calculation complete.");
Console.WriteLine("--------------------------------------------------");
// 8. File Export for the "Mega-Results"
if (actualDigits > 1000)
{
Console.Write("Save all digits to a text file? (y/n): ");
if (Console.ReadLine()?.ToLower() == "y")
{
File.WriteAllText("exponent_result.txt", fullResult);
Console.WriteLine("Success! Saved as 'exponent_result.txt'.");
}
}
Console.WriteLine("\nPress Enter to return to menu...");
Console.ReadLine();
}
//static void Square() { UnaryOp("SQUARE", x => x * x); Console.ReadLine(); }
//static void Cube() { UnaryOp("CUBE", x => x * x * x); Console.ReadLine(); }
static void Square() => BigDecUnaryOp("SQUARE", x => x * x);
static void Cube() => BigDecUnaryOp("CUBE", x => x * x * x);
static void Factorial()
{
// 1. Get Input
int n = GetInt("integer (0-100000)");
if (n < 0 || n > 100000)
{
Console.WriteLine("\nPlease use a number between 0 and 100,000.\n");
return;
}
// 2. Predict Digit Count using Stirling's Approximation (Logarithms)
// Formula: log10(n!) approx n*log10(n/e) + log10(sqrt(2*pi*n))
double predictedDigits = 0;
if (n > 0)
{
predictedDigits = (n * Math.Log10(n / Math.E)) + (Math.Log10(2 * Math.PI * n) / 2.0) + 1;
}
else { predictedDigits = 1; }
int predictedCount = (int)Math.Floor(predictedDigits);
Console.WriteLine($"\nPrediction: This result will have approx. {predictedCount:N0} digits.");
// 3. Safety Check for 4GB RAM
if (predictedCount > 1000000)
{
Console.WriteLine("🚨 WARNING: This will generate over 1 million digits.");
Console.WriteLine("Your CPU may handle it, but it will take a few minutes. Continue? (y/n)");
if (Console.ReadLine()?.ToLower() != "y") return;
}
// 4. User Preference
Console.Write("How would you like to see the result?\n[S] Shortened (Scientific) or [D] All Digits? (s/d): ");
string mode = Console.ReadLine()?.ToLower() ?? "s";
Console.WriteLine("\nCalculating... (This may take time for large numbers)");
// 5. The Math
BigInteger result = 1;
for (int i = 2; i <= n; i++)
{
result *= i;
}
// 6. The "Formatting" Bottleneck
string fullResult = result.ToString();
int digitCount = fullResult.Length;
Console.WriteLine("--------------------------------------------------");
Console.WriteLine($"{n}! = ");
if (mode == "s" && digitCount > 25)
{
Console.WriteLine($"{fullResult[0]}.{fullResult.Substring(1, 10)}... x 10^{digitCount - 1}");
}
else
{
Console.WriteLine(fullResult);
}
// 7. Status & Results
Console.WriteLine($"\nDONE! Total Digits: {digitCount:N0}");
if (digitCount > 308)
Console.WriteLine("Status: 🚀 Infinity Broken successfully!");
else
Console.WriteLine("Status: ✅ Calculation complete.");
Console.WriteLine("--------------------------------------------------");
// 8. File Saving Logic
if (digitCount > 1000)
{
Console.Write("\nSave all digits to a text file? (y/n): ");
if (Console.ReadLine()?.ToLower() == "y")
{
File.WriteAllText("factorial_result.txt", fullResult);
Console.WriteLine("Done! Created 'factorial_result.txt'.");
}
}
Console.WriteLine("\nPress Enter to return to menu...");
Console.ReadLine();
}
static void RunTestSuite()
{
Console.Clear();
Console.WriteLine("=== ENGINE STRESS TEST: 500-DECIMAL VERIFICATION ===");
// Define test cases: { Expression, Expected Description }
string[,] tests = {
{ "((1.5 + 2.5) * 2) ^ 3", "Whole number result from decimals" },
{ "1 / 3", "Infinite repeating decimal (Capped at 500)" },
{ "1.23456789 * 9.87654321", "High precision multiplication" },
{ "(10 + 5) / (2 * 3)", "Bracket precedence with division" },
{ "2 ^ 10", "Exponential growth test" }
};
for (int i = 0; i < tests.GetLength(0); i++)
{
string expr = tests[i, 0];
string desc = tests[i, 1];
try {
string result = Evaluate(expr);
Console.WriteLine($"\nTEST {i + 1}: {desc}");
Console.WriteLine($"EXPR: {expr}");
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"RESULT: {(result.Length > 80 ? result.Substring(0, 75) + "..." : result)}");
Console.ResetColor();
}
catch (Exception ex) {
Console.WriteLine($"TEST {i + 1} FAILED: {ex.Message}");
}
}
Console.WriteLine("\n--------------------------------------------------");
Console.WriteLine("ALL TESTS COMPLETE. SYSTEM STABLE.");
Console.WriteLine("--------------------------------------------------");
Console.ReadLine();
}
//static void BinaryOp(string name, Func<double, double, double> op) {
//double a = GetDouble("First Number");
//double b = GetDouble("Second Number");
// Console.WriteLine($"\n{name}: {op(a, b):F6}");
//}//
//static void UnaryOp(string name, Func<double, double> op) {
//double x = GetDouble("NUMBER");
//Console.WriteLine($"\n{name}: {op(x):F6}");
//}
static double GetDouble(string prompt) {
while (true) {
Console.Write($" Enter {prompt}: ");
if (double.TryParse(Console.ReadLine(), CultureInfo.InvariantCulture, out double result)) return result;
Console.WriteLine(" Invalid number!");
}
}
static int GetInt(string prompt) {
while (true) {
Console.Write($" Enter {prompt}: ");
if (int.TryParse(Console.ReadLine(), out int result)) return result;
Console.WriteLine(" Invalid integer!");
}
}
static BigInteger BigIntSquareRoot(BigInteger n)
{
if (n < 0) throw new ArgumentException("Negative number");
if (n < 2) return n;
// Fast bit-shift initial guess
BigInteger x = n >> (n.ToByteArray().Length * 4);
if (x < 1) x = n / 2;
BigInteger lastX;
do
{
lastX = x;
x = (x + n / x) >> 1;
} while (BigInteger.Abs(x - lastX) > 1);
return x;
}
static void BigDecBinaryOp(string name, Func<BigInteger, BigInteger, BigInteger> operation)
{
Console.WriteLine($"\n--- {name} MODE (Max 500 Decimals) ---");
Console.Write("Enter first number: ");
string s1 = (Console.ReadLine() ?? "0").Trim();
Console.Write("Enter second number: ");
string s2 = (Console.ReadLine() ?? "0").Trim();
int dot1 = s1.IndexOf('.');
int dot2 = s2.IndexOf('.');
int places1 = dot1 < 0 ? 0 : s1.Length - dot1 - 1;
int places2 = dot2 < 0 ? 0 : s2.Length - dot2 - 1;
// Determine how many decimal places we are tracking
int maxPlaces = Math.Max(places1, places2);
// Normalize (Align decimal points)
string clean1 = s1.Replace(".", "") + new string('0', maxPlaces - places1);
string clean2 = s2.Replace(".", "") + new string('0', maxPlaces - places2);
if (BigInteger.TryParse(clean1, out BigInteger n1) && BigInteger.TryParse(clean2, out BigInteger n2))
{
BigInteger result = operation(n1, n2);
string resStr = result.ToString();
bool isNegative = resStr.StartsWith("-");