How to get number of digits divisible by 5 - c#

I want to find the total number of digits divisible by 5 between 1 - 100, in C# windows form, how to proceed from here?
int sum;
private void button2_Click(object sender, EventArgs e)
{
int[] intarray = new int[100];
for (int i = 0; i < 99; i++)
{
intarray[i] = i + 1;
}
foreach (int a in intarray)
{
if (a / 5 == 0)
{
}
}
}

Note than a / 5 == 0 is wrong. For example 10 is divisible by 2, the result is 10/5 = 2, not equal to 0.
if (a % 5 == 0)
{
//then a is divisible by 5. print or store it
}
The modulus operator, also known as Remainder, returns the remainder of the integer division.
Therefore, the full answer:
int nInRange = 0;
foreach (int a in intarray)
if (a % 5 == 0)
nInRange++;

Maybe this is what you want.
public static IEnumerable<int> GetIntsDivisible(int start, int finish, int divisor)
{
for (var i = start; i <= finish; i++)
if (i % divisor == 0)
yield return i;
}
public static void Main()
{
Console.WriteLine(string.Join(", ", GetIntsDivisible(1, 100, 5)));
}
or if you don't want to yield
public static List<int> GetIntsDivisible(int start, int finish, int divisor)
{
var result = new List<int>();
for (var i = start; i <= finish; i++)
if (i % divisor == 0)
result.Add(i);
return result;
}
Output
5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100
Full demo here

Initialize a variable as 0
for e.g. Count = 0;
then add statement Count++ in your if block as follows:
if (a % 5 == 0)
{
Count++;
}

Since question is a bit vague in exact requirement, I will write the basic logic that can find the numbers exactly divisible by other number.
There is something called modulus (%) operator. It gives you the remainder of division.e.g. 11%5 will be 1, 13%5 will be 3, whereas 15%5 will be 0
so logic goes like,
for(int i=0;i<=100;i++)
{
if((i%5)==0)
{
\\this is ur number
}
}

Every one has address your question but no one talk about this weird attempt.
I really think you should take 5 minute and read your code because you are just running everywhere.
You should take the pen and paper before going head first into coding.
Here is a simple reading of your code so you understand what you were doing.
Line 1:
int[] intarray = new int[100];
So you start win an array, I guess it's for the result, right ? You will not be storing the number from 1 to 100 for no reason?
Line 2:
for (int i = 0; i < 99; i++)
Now we count from 0 to 98, I though it was form 1 to 100 .. Yes 98 as you are using < instead of <=
Line 3:
intarray[i] = i + 1;
Why ? 3rd line and you are already lost! You are filling the array with number you just iterate. It's like filling a bottle with water, then use it to fill an other bottle because you needed water.
If you iterate from 1 to 100 you could have check if it was divisible.
for (int i = 1; i <= 100; i++)
Line 4:
foreach (int a in intarray)
Again ? We are back counting from 1 to 100..
Line 5:
if (a / 5 == 0)
If this is suppose to tell you if it divisible thats wrong. The correct math operator is the Modulo. The division symbole won't give you the result you expect.
{1,2,3,4} will give you True. Anything else will be false.

int count = 0;
for (int i = 1; i <= 100; i++)
{
if ((i % 5) == 0)
{
count++;
textBox1.Text = count.ToString();
}
}
Alternatively,
int num = (100 + 5) / 5 - (1 + 5 - 1) / 5;
//Show result here

Related

Project Euler #1, getting higher results for no apparent reason

I'm having a problem with the first coding challenge on the Project Euler website. This is what you have to do:
"If we list all the natural numbers below 10 that are multiples of 3
or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."
Here's my code (c#):
total = 0;
for (int i = 0; i <= (999 - (999 % 3)) / 3; i++)
{
total += 3 * i;
}
for (int i = 0; i <= (999 - (999 % 5)) / 5; i++)
{
total += 5 * i;
}
When I return total it gives me '266333' while it should be '233168'. I've been staring at it for about an hour and I have no clue where my code is going wrong. Sorry if this is a stupid question but google isn't helping me and I feel really dumb.
You can do in single for loop as :
int total = 0;
for (int i = 1; i < 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
total += i;
}
}

How can I extract the places values of a number?

I'm working on a math game in the Unity game engine using C#, specifically a reusable component to teach the grid method for multiplication. For example, when given the numbers 34 and 13, it should generate a 3X3 grid (a header column and row for the multiplier and multiplicand place values and 2X2 for the number of places in the multiplier and multiplicand). Something that looks like this:
My issue is that I don't know the best way to extract the place values of the numbers (eg 34 -> 30 and 4). I was thinking of just converting it to a string, adding 0s to the higher place values based on its index, and converting it back to an int, but this seems like a bad solution. Is there a better way of doing this?
Note: I'll pretty much only be dealing with positive whole numbers, but the number of place values might vary.
Thanks to all who answered! Thought it might be helpful to post my Unity-specific solution that I constructed with all the replies:
List<int> GetPlaceValues(int num) {
List<int> placeValues = new List<int>();
while (num > 0) {
placeValues.Add(num % 10);
num /= 10;
}
for(int i = 0;i<placeValues.Count;i++) {
placeValues[i] *= (int)Mathf.Pow(10, i);
}
placeValues.Reverse();
return placeValues;
}
Take advantage of the way our number system works. Here's a basic example:
string test = "12034";
for (int i = 0; i < test.Length; ++i) {
int digit = test[test.Length - i - 1] - '0';
digit *= (int)Math.Pow(10, i);
Console.WriteLine("digit = " + digit);
}
Basically, it reads from the rightmost digit (assuming the input is an integer), and uses the convenient place value of the way our system works to calculate the meaning of the digit.
test.Length - i - 1 treats the rightmost as 0, and indexes positive to the left of there.
- '0' converts from the encoding value for '0' to an actual digit.
Play with the code
Perhaps you want something like this (ideone):
int n = 76302;
int mul = 1;
int cnt = 0;
int res[10];
while(n) {
res[cnt++] = (n % 10) * mul;
mul*=10;
cout << res[cnt-1] << " ";
n = n / 10;
}
output
2 0 300 6000 70000
My answer is incredibly crude, and could likely be improved by someone with better maths skills:
void Main()
{
GetMulGrid(34, 13).Dump();
}
int[,] GetMulGrid(int x, int y)
{
int[] GetPlaceValues(int num)
{
var numDigits = (int)Math.Floor(Math.Log10(num) + 1);
var digits = num.ToString().ToCharArray().Select(ch => Convert.ToInt32(ch.ToString())).ToArray();
var multiplied =
digits
.Select((d, i) =>
{
if (i != (numDigits - 1) && d == 0) d = 1;
return d * (int)Math.Pow(10, (numDigits - i) - 1);
})
.ToArray();
return multiplied;
}
var xComponents = GetPlaceValues(x);
var yComponents = GetPlaceValues(y);
var arr = new int[xComponents.Length + 1, yComponents.Length + 1];
for(var row = 0; row < yComponents.Length; row++)
{
for(var col = 0; col < xComponents.Length; col++)
{
arr[row + 1,col + 1] = xComponents[col] * yComponents[row];
if (row == 0)
{
arr[0, col + 1] = xComponents[col];
}
if (col == 0)
{
arr[row + 1, 0] = yComponents[row];
}
}
}
return arr;
}
For your example of 34 x 13 it produces:
And for 304 x 132 it produces:
It spits this out as an array, so how you consume and display the results will be up to you.
For two-digit numbers you can use modulo
int n = 34;
int x = n % 10; // 4
int y = n - x; // 30

C# subtract list from number in all possible ways so the resultant number is bigger than 0

I need to subtract list from a number, so the resultant number will be equal or bigger than 0 with a smallest result possible. Also I need to see which items of the list were subtracted.
int a = 10;
List<int> list = new List<int>();
I've tried this (probably really bad idea):
for (int c = 0; c < list.Count; c++)
{
if (a > 0)
{
a = a - list.ElementAt(c);
if (a < 0)
{
a = a + list.ElementAt(c);
}
else
{
Console.Write("{0}", list.ElementAt(c));
}
}
}
But the problem is that it only subtract in one way and doesn't find the best option.
Thanks for any ideas.
I believe the OP is looking to find smallest possible result after subtraction, but that result has to be greater than or equal to zero.
For example, in case of {13, 12, 11, 9} and the given number being 10 the result after subtraction should be {3,2,1,-1} for each list item respectively, in that case the final result should be 1 as it is minimum value, but greater than or equal to zero.
In that case the code could look like:
int a = 10;
List<int> list = new List<int> {13, 12, 11, 9};
int min = -1;
for (int c = 0; c < list.Count; c++)
{
int tempResult = list[c] - a;
if (tempResult >= 0)
{
min = tempResult;
}
}
Console.WriteLine(min);

Smallest cost traversal of an array

How do you compute the smallest cost traversal of an integer array using steps and jumps, while also counting the first and last element of the array? A step is moving to the next immediate value in the array e.g. array[currentIndex + 1], and a jump is moving two spots e.g. array[currentIndex + 2]. I have the following function which I want to return the minimum sum started, it adds the first and last elements to the sum, but I'm stuck on the middle values of the array.
An example of this would be {2, 10, 4, 14, 44, 28, 16, 18} -> 66
which would add indexes 0, 2, 3, 5, and 7.
====
public int Cost(int[] board)
{
int sum = board[0];
int index = 0;
while (index < board.Length)
{
//Add the final array value to the sum
if (index + 1 == board.length)
{
sum += board[index];
break;
}
//Add other values here
index++;
}
return sum;
}
You can try this:
public int Cost(int[] board)
{
int[] cost = new int[board.Length];
for (int i = 0; i < board.Length; i++) {
if (i == 0) {
cost[i] = board[0];
} else if (i == 1) {
cost[i] = board[1] + cost[0];
} else {
cost[i] = board[i] + Math.Min(cost[i - 1], cost[i - 2]);
}
}
return cost[board.Length - 1];
}
One possible solution:
public int Cost(int[] board, int step = 1)
{
if (board == null) return -1;
if (board.Length == 0) return 0;
// always add first and last index (if its not the first)
int sum = board[0];
if (board.Length > 1) sum += board[board.Length - 1];
// assumes step is > 0
for (int i = step; i < (board.Length - 1); i += step)
{
sum += board[i];
}
return sum;
}
This allows for step to be a parameter. Maybe now you want to step either 1 or 2 away from the start. Maybe later you want to step 5 spots away.

Flat Roulette with random number: get interval where random belongs to

For example i have and array with such elements:
0 21 29 0 0 50
let's "flat" this numbers:
let's say my random number is 54, so my number belongs to the last element in my array with index 6 (it's 50)
i can't understand, how to algorytmize that... with c#
i try:
Random random = new Random();
int randomNumber = random.Next(1, 100);
int temp, temp_ind;
float a_, b_;
for (j = 0; j < n-1; j++)
{
if (roulette[j] != 0)
{
temp_ind = j+1;
a_ = roulette[j];
while ((roulette[temp_ind] == 0.0) && (temp_ind < n-1))
{
temp_ind++;
}
b_ = roulette[temp_ind];
if ((a_ <= randomNumber) && (b_ >= randomNumber))
{
start = j;
break;
}
}
}
but this doesn't work, maybe something could help me?
Here's a solution which converts the array to a cumulative array (using an extension method from this answer by Eric Lippert), then finds the index of the first match in that array which is higher than the random number.
class Program
{
static void Main(string[] args)
{
var random = new Random();
int[] roulette = { 0, 21, 29, 0, 50 };
var cumulated = roulette.CumulativeSum().Select((i, index) => new { i, index });
var randomNumber = random.Next(0, 100);
var matchIndex = cumulated.First(j => j.i > randomNumber).index;
Console.WriteLine(roulette[matchIndex]);
}
}
public static class SumExtensions
{
public static IEnumerable<int> CumulativeSum(this IEnumerable<int> sequence)
{
int sum = 0;
foreach (var item in sequence)
{
sum += item;
yield return sum;
}
}
}
You have hopelessly too many variables, overcomplicating the problem. Beyond the counter and the number, you only need one additional variable to keep track of the closest smaller number.
Below is some code I wrote which has essentially the same idea, it just seems a bit simpler.
int[] roulette = {0, 21, 29, 0, 0, 50};
int closest = -1;
int number = 54;
for (int j = 0; j < roulette.Length; j++)
// if the values isn't 0 and it's smaller
// and we haven't found a smaller one yet, or this one's closer
if (roulette[j] != 0 && roulette[j] < number &&
(closest == -1 || roulette[j] > roulette[closest]))
{
closest = j;
}
if (closest == -1) // no smaller number found
Console.WriteLine(0);
else
Console.WriteLine(roulette[closest]);
Live demo.
For repeated queries, it would be better to sort the numbers, then do a binary search to find the correct position.

Categories