I was working on problem one and my original program looked like this
int multiplesof=1000,count=0, multiple1 = 3, multiple2 = 5,val1,val2,sum=0;
while (count < multiplesof)
{
if (count % multiple1 == 0)
sum = sum += count;
if (count % multiple2 == 0)
sum = sum += count;
count++;
}
Console.Out.WriteLine(sum + " is the sum of all multiples");
Console.In.ReadLine();
It give me the solution of 266333. This proved to be wrong, stumped I looked at Google. I have since gotten the correct value of 233168 with the following loop. However to me they look like they do exactly the same thing. Could anyone please explain why they are bring up different answers?
while (count < multiplesof)
{
if (count % multiple1 == 0 || count % multiple2 == 0)
sum = sum += count;
count++;
}
Because you added twice if it was a multiple of both 3 and 5, like when it was 15.
An alternative solution and also a spoiler if you were going to try to solve it yourself:
int result = 3 * (999 / 3 * (999 / 3 + 1) / 2) + 5 * (999 / 5 * (999 / 5 + 1) / 2) - 15 * (999 / 15 * (999 / 15 + 1) / 2);
Think about numbers that are divisible by both 3 and 5, such as 15. Your first attempt counts them twice.
Related
So im writing a small little c# console app, which is supposed to imitate a shopping system of sorts.
All the products are sold in Packs (not individually), and the Pack sizes are like 4 items, 10 items or 15 items.
Given a Qty size of like 28, it should return a result of something like:
2 x 10 Packs + 2 x 4 Packs.
Or given a Qty size of like 25, it should return a result of something like:
1 x 15 Packs + 1 x 10 Packs
And the function needs to be efficient, so it returns the least amount of packs.
(obviously ignore scenerio's where it might be an Qty of 3 - as there are no pack sizes that small)
this is my code at the moment:
qty = 28, LargePack = 15, MediumPack = 10, SmallPack = 4
double total = 0.00;
int tmpQty = qty;
while (tmpQty != 0)
{
if ((tmpQty >= LargePack) && ((tmpQty % LargePack) % 1) == 0)
{
tmpQty -= LargePack;
lg += 1;
total =+ (lg * LargePrice);
}
else if ((tmpQty >= MediumPack))
{
tmpQty -= MediumPack;
md += 1;
total =+ (md * MediumPrice);
}
else if ((SmallPack !=0) && (tmpQty >= SmallPack) && (tmpQty < MediumPack))
{
tmpQty -= SmallPack;
sm += 1;
total =+ (sm * SmallPrice);
}
}
My idea here - because with a qty of like 28, i need it to skip the first IF statement, i thought i'd do a check of whether tmpQty (28) / LargePack (15) was an integer number - which it shouldn't be, then it would go to the 2nd IF statement. But for some reason the formula:
(tmpQty % LargePack) %1 == 0
always equals 0 - so its True... when it should be false.
Or if anyone has a better way to work out Pack sizes, im open to suggestions.
Note - Pack sizes aren't defined here, as various different products use the same sorting process.
Your biggest issue is you don't understand what % does. It doesn't return a decimal. It works like the "remainder" from gradeschool division. 7 % 5 will return 2. If you want to keep your same logic (expecting a percentage) then you need to divide but your variables will need to be doubles or floats. If not, C# will cast the result to an integer, which has no decimal. I hope that helps.
(Anything % 1) always returns 0. That's why your condition is not working.
Try this
(tmpQty % LargePack) >= 0
Use:
if ((tmpQty >= LargePack) && ((tmpQty % LargePack) == 0))
This will return true only for values that are exactly divisible by LargePack, so in this case 28 would fail and move on.
Here is a brute force approach. At first we need a method to generate all combinations of an array of sequences. It is called CartesianProduct, and an implementation is shown below:
public static IEnumerable<T[]> CartesianProduct<T>(IEnumerable<T>[] sequences)
{
IEnumerable<IEnumerable<T>> seed = new[] { new T[0] };
return sequences.Aggregate(
seed,
(accumulator, sequence) => accumulator
.SelectMany(_ => sequence, (product, i) => product.Append(i))
).Select(product => product.ToArray());
}
We will need this method because we need all possible combinations of pack sizes and quantities. For example for pack sizes [5, 8] and quantity 21, the combinations we want to produce are these:
0*5 + 0*8 = 0
0*5 + 1*8 = 8
0*5 + 2*8 = 16
1*5 + 0*8 = 5
1*5 + 1*8 = 13
1*5 + 2*8 = 21
2*5 + 0*8 = 10
2*5 + 1*8 = 18
2*5 + 2*8 = 26
3*5 + 0*8 = 15
3*5 + 1*8 = 23
3*5 + 2*8 = 31
4*5 + 0*8 = 20
4*5 + 1*8 = 28
4*5 + 2*8 = 36
The last step will be to select the best combination. Here is the method that makes all these to happen:
private static (int PackSize, int Quantity)[] GetBestCombination(
int[] packSizes, int quantity)
{
var sequences = packSizes
.Select(p => Enumerable.Range(0, (quantity / p) + 1)
.Select(q => p * q))
.ToArray();
var cartesianProduct = CartesianProduct(sequences);
int[] selected = null;
int maxValue = Int32.MinValue;
foreach (var combination in cartesianProduct)
{
int sum = combination.Sum();
if (sum > quantity) continue;
if (sum > maxValue)
{
maxValue = sum;
selected = combination;
}
}
if (selected == null) return null;
return selected.Zip(packSizes, (sum, p) => (p, sum / p)).ToArray();
}
Lets test it:
var bestCombo = GetBestCombination(new[] { 5, 8 }, 21);
foreach (var pair in bestCombo)
{
Console.WriteLine($"{pair.Quantity} x {pair.PackSize}");
}
Output:
1 x 5
2 x 8
I'm supposed to code a program that writes out a division just like in school.
Example:
13:3=4.333333333333
13
1
10
10
10....
So my approach was:
Solve the division then get the solution in a List.
Then question if the first number (in this case 1) is divisible by 3.
If not put it down and add the second number and so on...
I managed to do this the first time. It's sloppy but works. The problem is that it only works with numbers that when divided get to have a decimal in it.
Exapmle:
123:13
This is the first code:
do
{
for (int number = 1; number <= divNum; number++)
if (number % divisor == 0) countH++;
for (int i = 0; i < count; i++)
Console.Write(" ");
if ((c = divNum % divisor ) < divisor )
{
Console.WriteLine(" " + ((divNum- (countH * divisor ))) * 10);
}
else Console.WriteLine(" " + (divNum- (countH * divisor )));
c = divNum % divisor ;
if (c < divisor )
{
divNum = c * 10;
}
count++; countH = 0;
} while ((divNum >= divisor ) && (count < x));
Any ideas or help? Sorry if this is a bad question.
************ added
Try of a better explanation:
1 cant be divided by 13, so it goes down, we get the 2 down and try 12 divided by 13, still nothing so we get the 3 down and try 123:13, 13 goes 9 times in 123 so we have 123-9*13 = 6 the six goes down we write 9 in the result. We try 6:13 not going so we drop a 0 next to 6. Next we try 60:13, 13 goes 4 times so 60-4*13 = 8, we get the 8 down. And so on..
123:13=9.46153....
123
60
80
20
70
50
....
Something like this should work. Not the fastest solution most likely, but should do the job.
var number = 123;
var b = 12;
int quotient;
double remainder = number;
var x = 10;
do
{
quotient = (int)Math.Floor(remainder / b);
remainder = remainder - (quotient * b);
for (int i = 0; i < count; i++)
Console.Write(" ");
remainder *= 10;
Console.WriteLine(" " + remainder);
count++;
} while ((remainder > 0) && (count < x));
I just started to learn C# and only know really basic stuff. So this question may be easy to you, but very hard to me. The more detail in your answer, the better.
The next line of code will check if a studentnumber is real or fake. The number is real when the sum of all the characters (when multiplied by their place number) are a multiple of 11.
Console.WriteLine("What is your studentnumber?");
stnum = Console.ReadLine();
var stnumint = Convert.ToInt32(stnum);
var ans1 = (stnumint % 10 - stnumint % 1) / 1;
var ans2 = (stnumint % 100 - stnumint % 10) / 10;
var ans3 = (stnumint % 1000 - stnumint % 100) / 100;
var ans4 = (stnumint % 10000 - stnumint % 1000) / 1000;
var ans5 = (stnumint % 100000 - stnumint % 10000) / 10000;
var ans6 = (stnumint % 1000000 - stnumint % 100000) / 100000;
var ans7 = (stnumint % 10000000 - stnumint % 1000000) / 1000000;
var control = ans1 * 1 + ans2 * 2 + ans3 * 3 + ans4 * 4 + ans5 * 5 + ans6 * 6 + ans7 * 7;
var endnum = control % 11;
if (endnum == 0)
{
Console.WriteLine("You have got a valid studentnumber.");
}
else
{
Console.WriteLine("Check if your studentnumber is correct. If it is, you are not a student.");
}
Take for example studentnumber 9232753. When calculating: (9*7 + 2*6 + 3*5 + 2*4 + 7*3 + 5*2 + 3*1) % 11, the answer will be 0.
How can I write this line of code into a smaller loop?
One equivalent loop would be:
int control = 0;
int power10 = 1; // var to save an expensive `Math.Power` call
for (int i = 1; i <= 7; i++)
{
control += ((stnumint % (power10*10) - stnumint % power10) / power10) * i;
power10 *= 10;
}
I would highly recommend not using var for built-in types like int, string, etc. You leave the resulting type at the mercy of the compiler which can give you unexpected results. Save var for when the actual type is difficult (or impossible) to determine at design-time.
var totalAns = 0;
for (int i = 1; i <= 10000000; i *= 10)
{
ans += (stnumint % (10*i) - stnumint % i) / i;
}
Here is the part for calculation. If you need to save stnumint, copy it another variable.
int stnumint=...; //must be sure, that data type is n
int checksum=0;
int i=1;
while(stnumint>0)
{
checksum=(stnumint%10)*i;
i++;
//in real numbers will look like floor(stnumint/10)
//will automaticly floor because of data type int
stnumint=stnumint/10;
}
Let say i have number 1 to 24, i want to get remainder of these from 12
so with mod 12 sequence would be 1 to 11 and additionally 0 (of 12 and 24) .
But i need this 0 to be always 12.
How to achieve such a thing in one liner(without additional variables or ifs).
Right now code is something like this:
for (int i = 1; i <= 24; i++)
{
Console.WriteLine(i % 12);
}
Oneline solution (with slight overhead though: i % 12 could be computed twice):
for (int i = 1; i <= 24; i++)
{
Console.WriteLine(i % 12 == 0 ? 12 : i % 12);
}
Pure arithmetic solution is
for (int i = 1; i <= 24; i++)
{
Console.WriteLine(12 - (12 - i % 12) % 12);
}
Another arithmetic options:
for (int i = 1; i <= 24; i++)
{
Console.WriteLine((i-1) % 12 + 1);
}
This simple makes sure the 'start' is moved one placed to the left (i-1) and corrects the outcome from 0 to 11 to 1 to 12 bij adding 1 to the result
I need compute (9173501 * 9173502 * 9173504) % 9173503 in C#; result = 2 but C# can't compute it.
If you have any idea please help me.
There is no need to use big integers.
Use this formula:
(x * y) % k = ((x % k) * (y % k)) % k
This way, you can apply the modulo to a product of two numbers, each of which will be < 9173503, so this product will fit in a long.
Note: the same holds true for addition:
(x + y) % k = ((x % k) + (y % k)) % k
And subtraction, with a slight change:
(x - y) % k = ((((x % k + k) % k) - ((y % k + k) % k)) % k + k) % k
It does not, however, hold for division:
(4 / 2) % 3 = 2
4 mod 3 = 1
2 mod 3 = 2
1 / 2 != 2
Convert your number to a BigInteger before you begin computations:
Console.WriteLine((new BigInteger(9173501)*9173502*9173504)%9173503);
// Output: 2
You can't directly compute it without BigInteger, but mathematically it's equivalent to:
((long)9173501 % 9173503) * (9173502 % 9173503) * (9173504 % 9173503) % 9173503
This is a math question, not a programming one.
As you see the numbers are really close to each other, so substituting n = 9173503 you will get: (n-2)(n-1)(n+1) % n.
Opening up the parenthesis you will get the following polynomial: n^3 - 2*n^2 - n + 2 and the remainder by n will be:
2 for every n > 2
0 for n = 1, 2
This means that not only (9173501 * 9173502 * 9173504) % 9173503 = 2, but also 13^127^61 * (13^127^61 + 1) * (13^127^61 + 3) % (13^127^61 + 2) is also 2, which is most probably can not be calculated with C# or other programming languages.