Can anybody help me with my code? my program shows wrong output, when i try to enter the number 2880 it shows 'Invalid Input'. the number 2880 is divisible by 20 right ? why does it go Invalid
int money, x[6],y[6],total;
x[0] = 1000; x[1] = 500; x[2] = 200; x[3] = 100; x[4] = 50; x[5] = 20;
system("cls");
printf("Enter your Money: ");
scanf("%d", &money);
total = money;
printf("\nBreakdown:\n");
for(int i=0;i < 6; i++){
y[i] = ( money - (money % x[i]) )/x[i];
money = (money % x[i]);
if (y[i] != 0)
printf("%10d x %d = %5d \n",x[i], y[i], (x[i] * y[i]));
}
printf("---------------------------\n");
printf("Total: %d",total);
if(money>0){
system("cls");
printf("Invalid Input !");
}
getch();
i am expecting my output will be like this:
Enter your Money: 2880
Breakdown:
1000 x 2 = 2000
500 x 1 = 500
200 x 1 = 200
100 x 1 = 100
20 x 4 = 80
---------------------------
Total: 2880
You could add an if clause in your for loop to ignore division by 50$ if the money is a multiple of 20, if that is what you actually want.
Otherwise, your program is doing exactly what you want it to do.
int money () {
int money, total;
int x[6] = { 1000, 500, 200, 100, 50, 20 };
int y[6] = { 0, 0, 0, 0, 0, 0 };
printf("Enter your money: ");
scanf("%d", &money);
total = money;
printf("\nBreakdown:\n");
for(int i=0; i<6; i++) {
if (x[i] == 50 && money % 20 == 0) {
continue;
}
y[i] = (money - (money % x[i]))/x[i];
money = (money % x[i]);
}
if (money > 0 && y[3] > 0) {
money += 50;
if (money % 20 == 0) {
y[5] = money / 20;
y[3] = y[3] - 1;
y[4] = y[4] + 1;
money = 0;
}
}
for(int i=0; i<6; i++) {
if (y[i] != 0) {
printf("\t %4d x%5d = %5d \n", x[i], y[i], (x[i] * y[i]));
}
}
printf("\t---------------------------\n");
printf("\t Total: %5d\n\n", total);
if(money > 0) {
printf("Invalid input!");
}
}
EDIT: I have added an if clause for sums like $2810 that has a remainder of 10$ (if decomposed in the standard manner) and can hence be differently decomposed. The idea is to check if by adding 50$, the remainder can be nicely divided into a number of 20$. This 50$ comes from breaking down an existing 100$.
E.g.
$210 is first decomposed into: $100 x 2, and a remainder of $10, hence INVALID
So, instead, we change a $100 into 2 x $50 such that we get
$100 x 1, $50 x 1, and a remainder of $10
We sum the $50 with the remaining $10 to get $60, which is broken down into $20 x 3
Therefore, we get $210 = 1 x $100, 1 x $50, 3 x $20.
Well, when I compiled this program, it worked successfully, just that the after showing the breakdown, it showed invalid input. I think you want to print invalid input when the money inputted is less than 0, as printing invalid input when money is more than 0 does not make sense. I think you should just change
if(money>0){
to
if(money<0){
Also, your breakdown is wrong, as it leaves 10 behind, and the sum just adds upto 2870 instead of 2880.
EDIT: You just now mentioned in your comment that you print invalid input when there is a remainder. Next time please mention that in the question, as in confuses the answerers of the question, just like I got confused. I'll get back with a solution, but I won't delete my original answer.
Related
I have a function prime factorization, but it works wierdly and I have no idea how to make it right.
It's expected to print factors through 'x' and write like 2^(power) or 3^(power) if 2's or 3's are reapeating factors.
MyOutput: 2 >> 22^2 | 6 >> 2 x 3^2 | 8 >> 22^22^3 | 9 >> 3 x 3^2.
How do I change this code to make it work properly.
Note: I have stated in main() that if num == 1: print 1.
void prime_factors(int num)
{
int power = 0;
for (int factor = 2; num > 1; ++factor)
{
while (num % factor == 0)
{
if (factor >= 3 && power >= 1)
printf(" x %d", factor);
else
printf("%d", factor);
num /= factor;
++power;
if (power >= 1)
{
printf("^%d", power);
}
}
}
}
There are four problems:
power is not being reset to 0 for each factor
It is printing factor even if power is 0.
It should not print the factor and power until power has been fully determined. (Currently, the code is printing every time power is incremented.
It prints x at the beginning if the first factor is > 2.
Fixed version below:
void prime_factors(int num)
{
int power = 0;
int first = 1;
for (int factor = 2; num > 1; ++factor)
{
power = 0;
while (num % factor == 0)
{
num /= factor;
++power;
}
if (power >= 1)
{
if (first)
printf("%d", factor);
else
printf(" x %d", factor);
printf("^%d", power);
first = 0;
}
}
}
There are various ways to speed it up.
One way to speed it up is to skip factors when they get too large (larger than the square root of num, as suggested by #chux in the comments), leaving num as the only remaining factor. Rather than calculating the square root, a simple division can be used, as shown in the // speed up 1 code section below:
void prime_factors(int num)
{
int power = 0;
int first = 1;
for (int factor = 2; num > 1; ++factor)
{
power = 0;
// speed up 1
if (num / factor < factor)
{
// skip impossible factors
factor = num;
}
// end of speed up 1
while (num % factor == 0)
{
num /= factor;
++power;
}
if (power >= 1)
{
if (first)
printf("%d", factor);
else
printf(" x %d", factor);
printf("^%d", power);
first = 0;
}
}
}
Another way to speed it up is to increment factor by 2 in the for loop most of the time, except when factor is 2, so the sequence will be 2, 3, 5, 7, 9, 11, etc.:
for (int factor = 2; num > 1; factor += 1 + (factor & 1))
The factor += 1 + (factor & 1) increments factor by 1 when factor is even, and increments factor by 2 when factor is odd, so the only even value of factor will be the initial value 2.
int min1, min2, won;
printf("parking minutes(분)? ");
scanf("%d", &min1);
min2 = (min1 - 30) % 10;
if (min1 <= 39)
won = 2000;
else {
if (min2 = 0)
won = 2000 + 1000 * (min1 - 30) % 10;
else
won = 2000 + 1000 * (min1 - min2 - 20) % 10;
}
printf("parking fee: %d", won);
The conditions of this program
until 30min, 2000won
after 30min, 1000won per 10min
max 25000won per a day
parking minutes cannot be over than 24 hours
I thought that '%' means remainder so I write like that but when I input 52, the results say 5200! I want to make result to be 5000. And I want to know what to do for condition 3 and 4. What can I do? Should I use 'for' and 'sum'?
Let's program the steps in the same order as the assignment:
int min1, min2, won;
printf("parking minutes(분)? ");
if (scanf("%d", &min1) != 1) {
printf("invalid input\n");
return 1; // invalid input.
}
won = 2000; // 1. until 30min, 2000won, minimum price
if (min1 > 30) {
// 2. after 30min, 1000won per 10min
min2 = min1 - 30; // minutes after 30
// add 1000won for every slice or 10min or portion thereof
won += ((min2 + 9) % 10) * 1000;
// 3. max 25000won per a day
if (won > 25000)
won = 25000;
}
// 4. parking minutes cannot be over than 24 hours
if (min1 > 24 * 60) {
// reject request
printf("parking time exceeds 24 hours\n");
} else {
printf("parking fee: %d\n", won);
}
The problem is with the condition of your inner if in else block.
if(min2 = 0)
One equal sign is assignment operator, you have to use == for equality check.
if(min2 == 0)
For school I am to write a C program that takes some amount of cash and returns the smallest number of coins it would take to reach that amount. I don't know what I am doing wrong. I've been tweaking and trying all sorts of different things but I cannot seem to totally debug the program.
The program gives correct answers to some inputs but overstates the amount of coins needed for many inputs.
Here is what I have so far.
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
while (n > 0)
{
while (n >= 25)
{
counter ++;
n = n - 25;
quarters ++;
printf("%i\n",n);
}
while (n >= 10 && n < 25)
{
counter ++;
n = n - 10;
dimes ++;
printf("%i\n",n);
}
while (n >= 5 && n < 10)
{
counter ++;
n = n - 1;
nickels++;
printf("%i\n",n);
}
while (n > 0 && n < 5)
{
counter ++;
n = n - 1;
pennies ++;
printf("%i\n",n);
}
}
printf("%d\n",counter + n);
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
I'm a bit surprised they're wanting you to use break to exit a loop, as you usually want loops to conclude "naturally" (and you usually save breaks for switch statements). Something like this should work, using integer division and the modulus operator (edit note: I'm using two ints instead of a single float because of inaccuracy with the latter. If someone more knowledgeable wants to show how to do it with float, would be interesting.):
#include <stdio.h>
int main() {
int dollar, cent;
int q = 0;
int d = 0;
int n = 0;
int p = 0;
int re;
printf("Enter amount: ");
scanf(" %d.%d", &dollar, ¢);
q = dollar * 4;
re = cent;
q = q + (re / 25);
re = re % 25;
d = re / 10;
re = re % 10;
n = re / 5;
re = re % 5;
p = re;
printf("q %d d %d n %d p %d\n", q, d, n, p);
return 0;
}
This approach also works if, for example, you're given the seconds and want to find the min:sec from that. If you're given 65 seconds, you do 65 / 60 for the minutes portion (which is 1), and the seconds portion is just the remainder after you divide by 60, or 65 % 60 (which is 5).
Here is a more complete answer that fits with the code that you gave us to start with. I changed the loops to subtraction/multiplication and fixed the bug where you were treating nickels as pennies. You don't need the counter variable anymore, but I left it in.
#include <stdio.h>
int main()
{
float cash;
int n;
int counter=0;
int quarters=0;
int dimes=0;
int nickels=0;
int pennies=0;
for (;;)
{
printf("Enter change amount: ");
scanf("%f",&cash);
if (cash > 0)
{
break;
}
}
n = cash * 100;
counter = 0;
if (n > 0)
{
quarters = (int)floor(n / 25);
n -= quarters*25;
printf( "%i\n", n );
dimes = (int)floor(n / 10);
n -= dimes*10;
printf("%i\n",n);
nickels = (int)floor(n / 5);
n -= nickels*5;
printf("%i\n",n);
pennies = n;
printf("%i\n",n);
}
printf("%i quarters, %i dimes, %i nickels, %i pennies\n",
quarters, dimes, nickels, pennies);
return 0;
}
First of all, try start with abstracting out how to handle one type of coin:
int coinsNeeded( int amount, int coinAmount )
{
return (int) floor( amount / coinAmount );
}
Then, handle each coin separately:
quarters = coinsNeeded( cash, 25 );
cash -= (quarters * 25);
Just repeat that for each type of coins you want to consider, and then print out the information at the end. There is some disagreement about whether you want to use floating points or not. Floating points do have rounding errors that you want to avoid when using money. what you actually need is a fixed point data type, but I digress. You can get close enough by doing it the way you're doing it (multiplying by 100 and just dealing with pennies).
Why I can not get a result of 2 while giving input of 2.2 as a float.
With my code, 2.2 should get converted to 220, and when it goes through the first for loop I should get a remainder of 20 (which is fine as it gives me 8 coins).
But when it goes through the second loop, I can not get 20/10 = 2, I always get 1.
By the way if I just put dime <= 20, I will get 2 hmm. I don't understand why since the remainder is equal to 20 as well.
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
float change ;
float quarter ;
float dime ;
float nickel ;
float penny = 1;
int coins = 0;
int coins1 = 0;
int coins2 = 0;
int coins3 = 0;
int sum = 0;
int remainder ;
do
{
printf("What is the owed change: \n");
change = GetFloat();
change = round(change * 100);
printf("%f\n", change);
}
while(change < 0);
for(quarter = 25; quarter <= change; quarter+=25)
{
remainder = change - quarter;
coins++;
}
printf("%d,%d\n", remainder,coins);
for (dime = 10; dime <= remainder; dime += 10) //This is where the problem starts.
{
remainder = remainder - dime;
coins1++;
}
printf("%d,%d\n", remainder,coins1);
for (nickel = 5; nickel < remainder; nickel += 5)
{
remainder = remainder - nickel;
coins2++;
}
printf("%d,%d\n", remainder,coins2);
for (penny = 1; penny < remainder; penny += 1)
{
remainder = remainder - penny;
coins3++;
}
printf("%d,%d\n", remainder,coins3);
printf("\n%d\n", sum = coins + coins1 + coins2 + coins3);
}
You're subtracting dime from remainder during each run of the for loop, while dime is being increased during each iteration of the loop. Let's suppose that change is initially 20 before the second for loop. The first loop execution will subtract 10, leaving remainderas 10. Then dime is incremented by 10 and is now 20. The loop condition fails because 20 > 10, and the loop runs only once.
My advice is to give your variables more intuitive names, like i or x for basic loop counters and dimes_needed instead of coins1
I am trying to write a code for calculating the number of trailing zeroes in a factorial of a specific number (large numbers). However, for small numbers, i get the correct result, but for large the deviations keeps increasing. What's wrong with my logic
#include <stdio.h>
int main(void) {
int t;
scanf("%d", &t);
while (t > 0) {
int factorten = 0, factorfive = 0, factortwo = 0, remainingfive = 0,
remainingtwo = 0;
unsigned int factors = 0;
unsigned int n;
scanf("%u", &n);
for (unsigned int i = n; i > 0; i--) {
if (i % 10 == 0) {
factorten++;
continue;
} else if (i % 5 == 0) {
factorfive++;
continue;
} else if (i % 2 == 0) {
// int new = i;
// while(new % 2 == 0)
//{
// new = new / 2;
factortwo++;
//}
continue;
}
}
factors = factors + factorten;
printf("%u\n", factors);
if (factorfive % 2 == 0 && factorfive != 0) {
factors = factors + (factorfive / 2);
} else {
remainingfive = factorfive % 2;
factors = factors + ((factorfive - remainingfive) / 2);
}
printf("%u\n", factors);
if (factortwo % 5 == 0 && factortwo != 0) {
factors = factors + (factortwo / 5);
} else {
remainingtwo = factortwo % 5;
factors = factors + ((factortwo - remainingtwo) / 5);
}
printf("%u\n", factors);
if ((remainingfive * remainingtwo % 10) == 0 &&
(remainingfive * remainingtwo % 10) != 0) {
factors++;
}
printf("%u\n", factors);
t--;
}
}
Sample Input:
6
3
60
100
1024
23456
8735373
Sample Output:
0
14
24
253
5861
2183837
My OUTPUT
0
13
23
235
5394
2009134
Edit: ignore the first two, they are suboptimal. The third algorithm is optimal.
I think this does what you're trying to do, but is a lot simpler and works:
int tzif(int n)
{
int f2 = 0, f5 = 0;
for (;n > 1; n--)
{
int x = n;
for (;x % 2 == 0; x /= 2)
f2++;
for (;x % 5 == 0; x /= 5)
f5++;
}
return f2 > f5 ? f5 : f2;
}
It counts 2-factors and 5-factors of numbers N...2. Then it returns the smaller of the two (because adding 2-factors is useless without adding 5-factors and vice-versa). Your code is too strange for me to analyze.
I think this should work too, because a factorial will have enough 2-factors to "cover" the 5-factors:
int tzif(int n)
{
int f5 = 0;
for (;n > 1; n--)
for (x = n;x % 5 == 0; x /= 5)
f5++;
return f5;
}
This only counts 5-factors and returns that.
Another method I think should work:
int tzif(int n)
{
int f5 = 0;
for (int d = 5; d <= n; d *= 5)
f5 += n / d;
return f5;
}
Count every fifth number (each has a 5-factor), then every 25-th number (each has another 5-factor), etc.
Have 3 counters - c2,c5,c10.
I think the checks should be
divisible by 5 but not by 10 -> c5++
divisible by 2 but not by 10 -> c2++
divisible by 10. Here if true, then count number of 0's. (c10++)
At last number of 0's will be
smaller_of(c2,c5) + c10
Try to code using this. Should work.
First the trailing 0 in N! are determined by factors 2 and 5 (10). The factors 2 always would be more that the factors 5 in this case you only need to calculate how factors 5 are in the N!.
(N!/5) would give you the number of multiple of 5 (5^1) in N!
(N!/25) would give you the number of multiple of 25 (5^2) in N!
(N!/125) would give you the number of multiple of 125 (5^3) in N!
...
(N!/5^n) would give you the number of multiple of 5^n in N!
When you add the multiple of 5 you are adding too the multiple of 25, 125, ..., 5^n, when you add multiple of 25 you are adding too the multiple of 125, ..., 5^n, etc...
In that case you only need to iterate the power of 5 less or equal than N and add the number of multiple of that 5 power.
Code:
long long trailing_zeros(long long N) {
long long zeros = 0;
for (long long power5 = 5; power5 <= N; power5 *= 5)
zeros += N / power5;
return zeros;
}
#include<iostream>
int main()
{
int size,i;
std::cin >> size;
int*fact;
fact = new int[size];
for (i = 0; i < size; i++)
{
std::cin >> fact[size];
}
for (i = 0; i < size; i++)
{
int con = 5;
int multiple = 0;
do
{
multiple = multiple+(fact[size] / con);
con = con * 5;
} while (con < fact[size]);
std::cout << multiple <<'\n';
}
return 0;
}
this code works perfectly for a single input..bt for multiple inputs it prints the o/p for the last entered number...what is wrong..i jst cant think off it