This week we began to learn the C# language. We learned about several fundamental types (int, bool, char, string) and a few control flow statements (if, while, for). We also learned about various operators.
To read about these topics, see ch. 1 "Introducing C#", ch. 2 "Data Types" and ch. 4 "Operators and Flow Control" of our Essential C# textbook.
We solved these exercises in the tutorial:
(Project Euler, problem 1)
Find the sum of all the multiples of 3 or 5 below 1000.
using static System.Console; class Program { static void Main(string[] args) { int sum = 0; for (int i = 0 ; i < 1000 ; i += 1) if (i % 3 == 0 || i % 5 == 0) sum += i; WriteLine(sum); } }
(Project Euler, problem 3)
What is the largest prime factor of the number 600851475143 ?
using static System.Console; class Program { static void Main(string[] args) { long n = 600_851_475_143; int i = 2; while (i * i <= n) if (n % i == 0) n /= i; else i += 1; WriteLine(n); } }
Consider a wheel with numbers 1 through 10. Write a program that reads two integers S and N on separate lines. S is the starting position of the wheel. N is a number of positions to turn the wheel, where a positive number indicates a counterclockwise rotation and a negative number is a clockwise rotation. The program should print a single integer indicating the final position of the wheel.
using static System.Console; class Program { static void Main(string[] args) { int s = int.Parse(ReadLine()); int n = int.Parse(ReadLine()); s = (s + n) % 10; if (s < 0) s += 10; if (s == 0) WriteLine(10); else WriteLine(s); } }
In number theory, the prime-counting function π(x) denotes the number of prime numbers that are less than or equal to x. Write a C# program that computes and prints π(1,000,000). Use trial division for primality testing.
using static System.Console; class Program { static void Main(string[] args) { int count = 0; for (int n = 2; n <= 1_000_000; ++n) { bool isPrime = true; int i = 2; while (i * i <= n) { if (n % i == 0) { isPrime = false; break; } i += 1; } if (isPrime) ++count; } WriteLine(count); } }