Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Hello I have tried to follow learning on codeasy.net, I have reached chapter 4 where it asks this:
Write a program that reads from the console three numbers each from the new line and then outputs the middle by the value of these three numbers.
Example:
>54
>4456
>2
54
I have tried all the code I know as a beginner and it is still wrong. My current code is this:
using System;
namespace ConsoleInput
{
public class TheMiddle
{
public static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
if (a < b && c < b)
Console.WriteLine(a);
if (a < b && b < c)
Console.WriteLine(b);
if (c < b && a < c)
Console.WriteLine(c);
if (a < b && c > b )
Console.WriteLine(a);
else
if (a > b && c > a)
Console.WriteLine(a);
if (a > b && b > c)
Console.WriteLine(b);
if (c > b && b > a)
Console.WriteLine(a);
if (b > a && c > a)
Console.WriteLine(c);
}
}
}
You need to make more comparisons. There are 3 cases.
if((a <= b && b <= c) || (c <= b && b <= a))
Console.WriteLine(b);
if((b <= a && a <= c) || (c <= a && a <= b))
Console.WriteLine(a);
if((a <= c && c <= b) || (b <= c && c <= a))
Console.WriteLine(c);
Basically the number is in the middle of the other two and you have to check the case where the the other two numbers are on either side. So for example b is in the middle if it's between a and c in that order, or between c and a in that order.
using System;
namespace ConsoleInput
{
public class TheMiddle
{
public static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
int result;
if (a < b)
{
if (c < a)
result = a;
else if (c > b)
result = b;
else
result = c;
}
else
{
if (c < b)
result = b;
else if (c > a)
result = a;
else
result = c;
}
Console.WriteLine(result);
}
}
}
this is the answer.
You can do this just by sorting your values and taking middle:
var list = new List<int>();
list.Add(a);
list.Add(b);
list.Add(c);
list.Sort();
var middleValue = list[list.Count/2];
Related
I have a task, that gives me a little headache here. The goal is to find Greatest Common Divisor with three integers, I succeded in doing it with two fairly easily, but with three it get's a little complicated when I can't use any arrays.
Here is the full code I used, finding gcd from two integers, tests all green:
public static int GetGcdByEuclidean(int a, int b)
{
if (a == 0 && b == 0)
{
throw new ArgumentException(null);
}
else if (a == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(a));
}
else if (b == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(b));
}
else
{
int abs1 = Math.Abs(a);
int abs2 = Math.Abs(b);
a = abs1;
b = abs2;
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a | b;
}
}
And now I used the same principle for the GCD by three, but used something I found on web: gcd(a, b, c) = gcd(a, gcd(b, c)) = gcd(gcd(a, b), c) = gcd(gcd(a, c), b)..
public static int GetGcdByEuclidean(int a, int b, int c)
{
int result = 0;
if ((a == 0 && b == 0) && c == 0)
{
throw new ArgumentException(null);
}
else if (a == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(a));
}
else if (b == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(b));
}
else if (c == int.MinValue)
{
throw new ArgumentOutOfRangeException(nameof(c));
}
else
{
int abs1 = Math.Abs(a);
int abs2 = Math.Abs(b);
int abs3 = Math.Abs(c);
a = abs1;
b = abs2;
c = abs3;
while (a != 0 && b != 0 && c != 0)
{
if (a > b && a > c && b > c)
{
b %= c;
a %= b;
result = a;
}
else if (a > b && a > c && b < c)
{
c %= b;
a %= c;
result = a;
}
else if (b > a && b > c && a > c)
{
a %= c;
b %= a;
result = b;
}
else if (b > a && b > c && a < c)
{
c %= a;
b %= c;
result = b;
}
else if (c > a && c > b && a > b)
{
a %= b;
c %= a;
result = c;
}
else
{
b %= a;
c %= b;
result = c;
}
}
return result;
}
}
Just keep your solution for 2 numbers and call it from the one for three numbers by using this formula: gcd(a, b, c) = gcd(a, gcd(b, c))
public static int GetGcdByEuclidean(int a, int b)
{
// Your working solution for two numbers...
}
public static int GetGcdByEuclidean(int a, int b, int c)
{
return GetGcdByEuclidean(a, GetGcdByEuclidean(b, c));
}
Note, in C# you can have several methods with the same name, as long as the parameter lists are different. The names of the parameters do not matter, only the number or types of the parameters must be different. This is called overloading.
A solution with an arbitrary number of numbers (but at least two):
public static int GetGcdByEuclidean(int a, int b, params int[] other)
{
int gcd = GetGcdByEuclidean(a, b);
foreach (int x in other) {
gcd = GetGcdByEuclidean(gcd, x);
}
return gcd;
}
This question already has answers here:
Check if number is prime number
(31 answers)
Closed 2 years ago.
I have a problem with my code and i don't know how to solve it. Basically this program prints prime numbers based on the user input and at the end it prints their sum. This works perfectly until a certain amount, example: if i input 10, it shows ten correct prime numbers, but if i input 100, it also prints a number that is not prime, in this case 533. I don't know where i'm wrong.
Thanks for the support.
EDIT: I solved it on my own. Basically there was an error in the first "If" inside the for loop, i've simply added "c = n - 1;" after n++. Now it works perfectly.
Console.Write("How many prime numbers?: ");
int l = Convert.ToInt32(Console.ReadLine());
int n = 2;
int sum = 0;
sum += n;
Console.WriteLine(n);
n++;
int i = 1;
l++;
while (i < l)
{
for (int c = n - 1; c > 1; c--)
{
if (n % c == 0)
{
n++;
}
else if (n % c != 0 && c == 2)
{
sum += n;
Console.WriteLine(n);
n++;
i++;
}
}
}
Console.WriteLine("Sum: " + sum);
Let's start from extracting method:
public static bool IsPrime(int value) {
if (value <= 1)
return false;
if (value % 2 == 0)
retutn value == 2;
int n = (int) (Math.Sqrt(value) + 0.5);
for (int d = 3; d <= n; d += 2)
if (value % d == 0)
return false;
return true;
}
Having this method implemented you can easily compute the sum of the first N primes:
int N = 100;
long s = 0;
for (int p = 1; N > 0; ++p) {
if (IsPrime(p)) {
s += p;
N -= 1;
}
}
Console.Write(s);
Another (a bit more complex) possibility is prime numbers enumeration:
public static IEnumerable<long> Primes() {
yield return 2;
List<int> knownPrimes = new List<int>();
for (int p = 3; ; p += 2) {
int n = (int) (Math.Sqrt(p) = 0.5);
bool isPrime = true;
foreach (int d in knownPrimes) {
if (d > n)
break;
if (p % n == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
knownPrimes.Add(p);
yield return p;
}
}
}
Then you can query enumeration with a help of Linq:
using System.Linq;
...
long s = Primes()
.Take(N)
.Sum();
I am trying to calculate the Greatest Common Divisor using a while loop. I am therefore looking for the greatest number (i.e. the last value of the loop). How do I get rid of the preceding numbers?
Example:
The greatest common divisor of 84 and 18 is 6. However, my code gives me the numbers 2, 3, and 6. What do I need to change to get only the last number?
using System;
namespace CalculateGCD
{
class Program
{
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int i = 1;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
}
}
}
}
}
Define a variable called max then print the max out of the while loop like this:
int max = 0;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
max = i;
}
}
Console.WriteLine("GCD:{0}", max);
Also if you are using C# 6 you could simplify your Console.WriteLine by using string interpolation like this:
Console.WriteLine($"GCD:{max}");
There is a simple solution which will calculate GCD
static int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
and you can use it like below
using System;
namespace CalculateGCD
{
public class Program
{
public static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine(GCD(a,b));
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}
}
You can invert the loop, insted of going from 1 to the Min between a and b, search from the Min to 1.
int i = Math.Min(a, b);
while (i > 0)
{
i--;
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
break;
}
}
simply reverse the enumeration sequence will do
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int i = Math.Min(a ,b);
while (i > 1)
{
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
break;//greatest will be the first
}
i--;
}
int gcd;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
gcd=i;
}
}
Console.WriteLine("GCD:{0}",gcd);
Save greatest common divisor in a variable.
I am trying to create a program that will give me every single digit between 1 and 55 but 6 times in a row.
That is;
1-17-25-45-49-51
55-54-53-52-51-50
Note, two numbers can never repeat in a row.
I've tested this program on a smaller scale and so far it does as intended. However, if I run it full scale, as the code posted bellow shows, it runs into an "out of memory exception". My guess is, its because of the memory having to hold such big numbers while building the ArrayList and file consecutively.
How do I go about fixing this?
class MainClass
{
public static void Main (string[] args)
{
ArrayList newWords= new ArrayList();
System.Console.WriteLine ("Please enter word to prepend ");
int wordCount = 0;
string numbers;
string word = Console.ReadLine ();
string word2 = word;
string separator = "-";
System.Console.WriteLine ("Please enter location of where you would like the new text file to be saved: ");
string newFileDestination = Console.ReadLine ();
TextWriter writeToNewFile = new StreamWriter (newFileDestination);
for(int a = 1; a < 56; a++){
for(int b = 1; b < 56; b++){
for(int c = 1; c < 56; c++){
for(int d = 1; d < 56; d++){
for(int e = 1; e < 56; e++){
for(int f = 1; f < 56; f++){
if(a != b && a != c && a != c && a != e && a != f && b != c && b != d && b != e && b != f && c != d && c != e && c != f && d != e && d != f && e != f){
word = word2;
numbers = string.Concat(a, separator, b, separator, c, separator, d, separator, e, separator, f);
word += numbers;
newWords.Add (word);
}
}
}
}
}
}
}
foreach(string line in newWords){
writeToNewFile.WriteLine(line);
Console.WriteLine (line);
wordCount++;
}
writeToNewFile.Close ();
Console.WriteLine (wordCount);
Console.WriteLine ("Press any key to exit.");
System.Console.ReadKey ();
}
}
}
Without trying to fix the rest of your code, the basic principle you need to follow is to write out the numbers as you get them, instead of cumulating them in a list. You can get rid of the ArrayList altogether, and the accompanying foreach loop.
The relevant part would look like this:
TextWriter writeToNewFile = new StreamWriter (newFileDestination);
for(int a = 1; a < 56; a++){
for(int b = 1; b < 56; b++){
for(int c = 1; c < 56; c++){
for(int d = 1; d < 56; d++){
for(int e = 1; e < 56; e++){
for(int f = 1; f < 56; f++){
if(a != b && a != c && a != c && a != e && a != f && b != c && b != d && b != e && b != f && c != d && c != e && c != f && d != e && d != f && e != f){
word = word2;
numbers = string.Concat(a, separator, b, separator, c, separator, d, separator, e, separator, f);
word += numbers;
writeToNewFile.WriteLine(word);
Console.WriteLine (word);
wordCount++;
}
}
}
}
}
}
}
But, be warned. Your code will take a long time to complete. You just won't get the out of memory error. You may run out of hard disk space though :)
I found this as a Microsoft interview question (see Round 4). I am trying to solve it using C#. My attempt:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 1) return a;
if (term == 2) return b;
if (term == 3) return c;
for (int i = 4; i <= term; i++)
{
a = a + b + c; if ((1 + 3 * i) % term == 0) { result = a; break; }
b = a + b + c; if ((2 * i + i - 1) % term == 0) { result = b; break; }
c = a + b + c; if ((3 * i) % term == 0) { result = c; break; }
}
return result;
}
But it is somehow not working var res = NTerm_Tribonacci(5);//should be 4 but getting 44
How can I solve this?
Tribonacci Number
Try this:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 0) result = a;
if (term == 1) result = b;
if (term == 2) result = c;
while(term > 2)
{
result = a + b + c;
a = b;
b = c;
c = result;
term--;
}
return result;
}
Note that as per the definition in your link, I have assumed the first term to be T0, not T1.
Demo
I like the "LINQ way" of solving such things:
public IEnumerable<long> InfiniteTribonacciSequence()
{
long a = 0, b = 1, c = 1;
long nextTerm;
yield return a;
yield return b;
yield return c;
while (true)
{
nextTerm = a + b + c;
yield return nextTerm;
a = b;
b = c;
c = nextTerm;
}
}
But this has to be used carefully, because Methods like Min() will go crazy with this. But you can use e.g. InfiniteTribonacciSequence.Take(5).Last() to get the 5th element of the sequence.
I think the recursive way is too suitable for such cases:
example:
using System.IO;
using System;
class Program
{
static void Main()
{
int a=4, b;
b=tribo(a);
Console.WriteLine(b);
}
static public int tribo(int n)
{
if(n==0) return 0;
if(n==1) return 1;
if(n==2) return 1;
return(tribo(n-1)+tribo(n-2)+tribo(n-3));
}
}
this gives the series 0 1 1 2 4 7 13 24 ...