I have printed some Fibonacci numbers. Now I want to see if a number / which I enter / is within that range and if it is, to show it's position.
This is what I have so far:
using System;
namespace SomeFibonacciPrimes
{
class SomeFibonacciPrimes
{
static void Main()
{
int first = 0;
int second = 1;
int third = 1;
for (int i = 0; i < 50; i++)
{
third = second;
second = first + second;
first = third;
Console.WriteLine(second);
}
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (number == second)
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
}
}
}
I can't understand why the If statement prints the else result if I enter a number that I SEE in the range?!
I think that after I manage to make the If statement to work, the position is the "i" in the for statement?
I suggest you to use either an array of integer or List of integer to solve this: as like the following:
int first = 0;
int second = 1;
int third = 1;
List<int> fibnoList= new List<int>();
for (int i = 0; i < 50; i++)
{
fibnoList.Add(second);
Console.WriteLine(second); //To print the series
third = second;
second = first + second;
first = third;
}
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (fibnoList.Contains(number))
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
Aside from using looping, maybe you can consider this
using System;
namespace SomeFibonacciPrimes
{
class SomeFibonacciPrimes
{
static void Main()
{
Console.WriteLine("Enter a number to find if it's in Fibonacci range:");
int number = int.Parse(Console.ReadLine());
if (IsFibonacci(number))
{
Console.WriteLine("Your number is within the Fibonacci range.");
}
else
{
Console.WriteLine("Your number is NOT within the Fibonacci range");
}
}
static bool IsFibonacci(int number)
{
//Uses a closed form solution for the fibonacci number calculation.
//http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
int n = (int) Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence
int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)
return actualFibonacciNumber == number;
}
}
}
Related
What I need is:
e.g:
Sum should be equal to:
120 (user input)
Number of numbers/items:
80 (user input)
Range of numbers to be used in set(from):
0 (user input)
Range of numbers to be used in set(to):
4 (user input)
Output:
1,1,3,2,1,1,0,0,1,1,2,1,0,2,3,3,1,2,0,0,0,1,3,2,3,1,0,0,2,3,2,3,2,2,1,1,0,0,2,0,1,0,1,1,3,3,1,3,1,0,0,3,2,1,0,0,2,1,2,3,0,3,1,1,3,3,2,2,1,1,3,1,3,3,3,3,3,1,2,0
These are all numbers that are between 0 and 4, their sum is 120 and are 80 in total.
What i've done is:
static void Main(string[] args)
{
bool loopOn = true;
Program p = new Program();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("");
Console.WriteLine("Sum should be equal to:");
int sum = int.Parse(Console.ReadLine());
Console.WriteLine("Number of items:");
int items = int.Parse(Console.ReadLine());
Console.WriteLine("Range(from):");
int from = int.Parse(Console.ReadLine());
Console.WriteLine("Range(to):");
int to = int.Parse(Console.ReadLine());
while (loopOn == true)
{
List<int> number_list = p.createNumberSet(items, from, to);
if (number_list.Sum() == sum)
{
loopOn = false;
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("Start");
number_list.ForEach(Console.WriteLine);
Console.WriteLine("Stop");
Console.WriteLine("____________________________________________________________________________");
}
}
Console.WriteLine("Press any key to exit....");
Console.ReadLine();
}
public List<int> createNumberSet(int itemNumber, int range_from, int range_to)
{
List<int> number_set = new List<int>();
Random r = new Random();
for (int i = 0; itemNumber > i; i++)
{
number_set.Add(r.Next(range_from, range_to));
}
return number_set;
}
But this seems extremely in-efficent and doesn't seem to work with a lot of other examples. Does anyone have a better way of doing this?
Well, I am a bit lazy right now, so this is just an idea
Keep the first part:
bool loopOn = true;
Program p = new Program();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("");
Console.WriteLine("Sum should be equal to:");
int sum = int.Parse(Console.ReadLine());
Console.WriteLine("Number of items:");
int items = int.Parse(Console.ReadLine());
Console.WriteLine("Range(from):");
int from = int.Parse(Console.ReadLine());
Console.WriteLine("Range(to):");
int to = int.Parse(Console.ReadLine());
Now, first of all, check is a solution exists:
if (from * items > sum) {
// There is no solution, handle accordingly
}
Let's focus on the interesting part now:
First create the list of necessary items
int[] number_set = new int[items];
for(int i = 0; i < items; i++) {
number_set[i] = from;
}
Find the difference between the wanted sum and the current sum of the list
int left_to_add = sum - from * items;
int idx = 0;
Random r = new Random();
while(left_to_add > 0) {
int toAdd = 0;
if (left_to_add < range_to - range_from) {
toAdd = r.Next(1, left_to_add);
} else {
toAdd = r.Next(1, range_to - range_from);
}
left_to_add -= toAdd;
number_set[idx] += toAdd;
idx++;
}
What's left to do is, convert the array to a list and shuffle it.
(I forgot that you actually can access list items by index, so there is no need to use an array as I did here)
At the algorithm level, this is what I would try:
Determine the number of each element, n[0], n[1], n[2], n[3] in your example (i.e. number of 0, number of 1 ...) and then generate a simple sequence by concatenating n[0] "0", n[1] "1", n[2] "2" and n[3] "3". Finally, a random sequence is obtained by performing a random permutation on this simple sequence.
The problem is therefore to determine the n[i].
The first step is to determine the average values of these n[i]. It your example, it is simple, as we can take average n_av[i]=20 for all index i.
In a more general case, we have to insure that
sum_i n_av[i]*i = sum_target (120 here) (1)
knowing that
sum_i (n[i]) = n = 80 here. (2)
In the general case, there is no necessary one unique good solution. I will try to propose an example of solution here if you provide an example of a difficult scenario.
The second step consists in selecting some random n[i] values around these average values. One possibility is to generate rounded Gaussian variables: we already know the averages, we just need to determine the variances. One possibility is to consider the variance that we will get if we were generating directly the random values, i.e. by considering the variance of the corresponding binomial variable :
var = n p(1-p). Here p[i] = n_av[i]/n
The last step consists in adjusting the values of the n[i] such that the sum of the n[i] is equal to the target. This is simply obtained by slightly increasing or decreasing some n[i] values.
I`m quite new to the whole programming world.
And i started studying C#
i got the following exersice to do:
Write a program that upon the input of 2 numbers (a and b), u receive
an output of the sum of squares in between.
I.e. - The program receives a and b where b > a and calculates a^2
+ (a+1)^2 + (a+2)^2 + ... + (b-1)^2 + b^2.
E.g. - If a = 3 and b = 6, the output would be 86, since 3^2 +
4^2 + 5^2 + 6^2 = 9 + 16 + 25 + 36 = 86
But i don't have any idea where do i even begin.
I`m guessing i need some sort of loop within a loop maybe?
You need to use for loop for this. Please see below, if that helps-
int i, j, k;
int value=0;
Console.WriteLine("Enter the fist number ");
i = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number ");
j = Convert.ToInt32(Console.ReadLine());
if (i > j)
{
Console.WriteLine("Second number should be greater then First");
Console.ReadLine();
Environment.Exit(0);
}
for (k = i; k <= j; k++)
{
value += k * k;
}
Console.WriteLine(value);
Console.ReadLine();
Perhaps a method that takes in two integers and returns a double is a good place to start (returning a double allows you to specify a wider range of numbers without getting inaccurate results):
public static double GetSumOfSquaresBetween(int first, int second)
{
}
Then you could implement the body by creating a loop that goes from the lowest number to the highest number, adding the square of the current number to a result, and then returning that result at the end.
Here's a Linq example that would most likely not be acceptable for this assignment but gives you the idea:
public static double GetSumOfSquaresBetween(int first, int second)
{
return Enumerable
.Range(Math.Min(first, second), Math.Abs(first - second) + 1)
.Select(number => Math.Pow(number, 2))
.Sum();
}
Try this
int a, b, sum = 0;
Console.WriteLine("Enter the fist number ");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter the second number ");
b = Convert.ToInt32(Console.ReadLine());
if (a<b){
for (int x = a+1; x < b; x++)
{
sum += x * x;
}
Console.WriteLine(sum);
}
else{
Console.WriteLine("Wrong input!");
}
Console.ReadLine();
}
}
A for loop should do it.
double nTotal = 0;
for (int a = 3; a <= 6; a++)
{
nTotal += Math.Pow(a, 2);
}
I wrote a code to find the sum of the digits and the reverse of a number-
static void Main(string[] args)
{
int number, sum = 0;
Console.WriteLine("Enter a number:");
number = int.Parse(Console.ReadLine());
while (number!= 0)
{
int m = number % 10;
number = number / 10;
sum = sum + m;
}
Console.WriteLine("Sum of digits of the number:" + sum);
Console.ReadLine();
int reverse = 0;
while (number!= 0)
{
reverse = reverse * 10;
reverse = reverse + number % 10;
number = number / 10;
}
Console.WriteLine("Reversed Number is:" + reverse);
Console.ReadLine();
}
but, the output for reversed number comes as 0. I checked my code, and I am not sure what is wrong with it.
You modify number as you sum the digits so when you try to go through the second loop, number is already at 0. Save off the input and reset number before the second loop:
Console.WriteLine("Enter a number:");
int input = int.Parse(Console.ReadLine());
number = input;
while (number!= 0)
{
// ...
}
Console.WriteLine("Sum of digits of the number:" + sum);
number = input; // reset number back to original input
// ...
There's also a possible solution to the problem using LINQ:
int number = 1234567890;
int sumOfDigits = number.ToString().Select(c => int.Parse(c.ToString())).Sum();
int reversedNumber = int.Parse(new string(number.ToString().Reverse().ToArray()));
Console.WriteLine($"sum of digits: {sumOfDigits}");
Console.WriteLine($"reversed number: {reversedNumber}");
I am new to C#. I have been working on this program and researching but am not getting anywhere. The goal is to have the user enter numbers (how many is up to the user). when they enter a 0, it will stop the program and display the minimum number entered, the maximum number entered, and the average of all numbers entered. I am not getting any errors and I am getting. If someone can please point me in the right direction.
The WriteLines are returning:
Lowest number is 0
Highest number is 0
Average is: 0
Count: 5
Here is my code:
int LOWEST =0;
int HIGHEST=0;
const int STOP = 0;
double average = 0;
int input;
int count = 0;
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
while (input != STOP)
{
for (int i=0; input != STOP; i++)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
count++;
var Out = new int[] { input };
LOWEST = Out.Min();
HIGHEST = Out.Max();
average = Out.Average();
if ((input > LOWEST) || (input < HIGHEST))
{
LOWEST = Out.Min();
}
if (input > HIGHEST)
{
HIGHEST = Out.Max();
}
}
}
Console.WriteLine("Lowest number is {0}", LOWEST);
Console.WriteLine("Highest number is {0}", HIGHEST);
Console.WriteLine("Average is {0}", average);
Console.WriteLine("Count: {0}", count);
Console.ReadLine();
On each run you are constructing a new array of integers:
var Out = new int[] { input };
After this line, Out contains one item: the last input. Calling Min, Max and Average on it will return the last value. Which is zero if you ended the program.
instead of creating a new array each time, you want to create a List<int> at the beginning of your program and then add each input to it. You can then use the whole list of values to calculate Min, Max and Average.
Eventually you can change your code into something like this:
const int STOP = 0;
int input = -1;
List<int> Out = new List<int>();
while (input != STOP)
{
Console.WriteLine("Enter a number. You can end the program at anytime by entering 0");
input = Convert.ToInt32(Console.ReadLine());
if (input == STOP) break;
Out.Add(input);
}
Console.WriteLine("Lowest number is {0}", Out.Min());
Console.WriteLine("Highest number is {0}", Out.Max());
Console.WriteLine("Average is {0}", Out.Average());
Console.WriteLine("Count: {0}", Out.Count);
Console.ReadLine();
List<int> numbers = new List<int>();
numbers.Add(10);
numbers.Add(30);
numbers.Add(20);
numbers.Add(0);
numbers.Max();
numbers.Min();
numbers.Average();
returns 30, 0 and 15.
Before your loop, you should probably make Out an extensible data structure analogous to an array, the List.
List<int> Out = new List<int>();
then each loop, you can
Out.Add(input);
Since this sounds like an exercise for the reader, you can then traverse your list and compute the average from all data values.
Alternately, before the loop, you could declare
int n = 0;
int total = 0;
and each loop, do
n += 1;
total += input;
From these, you should be easily able to compute the average.
I have a method that needs to do a calculation based upon the length of an array. I am using the .length method for the calculation, but the method is doing arithmetic with the max length of the array (which I have declared as 10). This is the loop I am using to get data from the user. I know it isn't the ideal way to sort array data, but this is for a homework assignment, and it revolves around using the .Split method correctly (which isn't the problem I'm having).
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
name [i] = separateInput[0];
score [i] = int.Parse(separateInput[1]);
}
Here is the method I am using to calculate the average score:
static void CalculateScores(int[] score)
{
int sum = 0;
int average = 0;
for (int i = 0; i < score.Length; i++)
{
sum += score[i];
average = sum / score.Length;
}
Console.WriteLine("The average score was {0}", average);
I am calling the method like this:
CalculateScores(score);
Edit: My arrays are declared:
int[] score = new int[MAX]; //MAX == 10.
string[] name = new string[MAX];
The CalculateScores method is doing the math as though score.Length is always 10, no matter how many different combinations of scores I input to the console. I can't figure out if it's because my loop to gather input has been done incorrectly, or my CalculateScores method is flawed. Thanks in advance.
Edit: to clarify, I am just confused at why I can't get the correct value out of CalculateScores.
Length always represents the size of the array, which if you've instantiated as 10, then it will always be 10, regardless of how many items you've filled.
There are lots of ways of solving your problem, but I'd go with the simple one of not using length in your calculation, but rather just storing the number of items in a separate variable:
int numItems = 0;
for(int i=0;i<MAX;i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
break; // if nothing is entered, it will break the loop
}
numItems++;
...
}
static void CalculateScores(int[] score, int numItems)
{
// don't use Length at all, use numItems instead
}
Arrays are generally used for fixed sized data, so the Length property reflects how many items the array can hold rather than the amount of elements in the array. The simplest fix would be to use a List(T), which is used for variadic data, instead.
// A nice abstraction to hold the scores instead of two separate arrays.
public class ScoreKeeper
{
public string Name { get; set; }
public int Score { get; set; }
}
var scores = new List<ScoreKeeper>();
for (int i = 0; i < MAX; i++)
{
Console.Write("Enter a name and a score for player #{0}: ", (i + 1));
string input = Console.ReadLine();
if (input == "")
{
// If nothing is entered, it will break the loop.
break;
}
// Splits the user data into 2 arrays (integer and string).
string[] separateInput = input.Split();
scores.Add(new ScoreKeeper { Name = separateInput[0], Score = int.Parse(separateInput[1]) });
}
static void CalculateScores(ICollection<ScoreKeeper> scores)
{
// We take advantage of Linq here by gathering all the
// scores and taking their average.
var average = scores.Select(s => s.Score).Average();
Console.WriteLine("The average score was {0}", average);
}
checking maually:
int sum = 0;
int average = 0;
int length;
for (int i = 0; i < MAX; i++) {
if(name[i]!=string.empty) {
sum += score[i];
length=i+1;
}
}
average = sum / length;
Console.WriteLine("The average score was {0}", average);