What I am trying to do in the code below is to to make the input a four-digit number (if it's not already) and then sort the digits in the number in an ascending and descending order. x is ascending, y is descending. Then I want to subtract x and y until I get the result 6174 of the subtraction.
#include <stdio.h>
int main() {
int number, count = 0, digit, pow = 0, result = 1, counter, temp,
x = 0, y = 0, i, j, substract = 0, count1 = 0;
scanf("%d", &number);
while (substract != 6174 && substract >= 0) {
substract = 0;
if (count1 > 0) {
temp = substract;
} else {
temp = number;
}
while (temp > 0) {
digit = temp % 10;
temp = temp / 10;
count++;
}
if (count < 4) {
pow = 4 - count;
/* Calculate base^exponent */
for (counter = 0; counter < pow; counter++) {
result = result * 10;
}
number = number * result;
}
for (i = 9, j = 0; i >= 0 && j <= 9; i--, j++) {
int tmpNumber = number;
while (tmpNumber > 0) {
int digit = tmpNumber % 10;
if (digit == i) {
x *= 10;
x += digit;
} else
if (digit == j) {
y *= 10;
y += digit;
}
tmpNumber /= 10;
}
}
substract = x - y;
count++;
printf("\n x %d", x);
printf("\n y %d", y);
printf("\n substract %d", x - y);
}
return 0;
}
When I input 3542 What I expect as an output is this
input:
3524
output:
x 5432
y 2345
subtract 3087
x 8730
y 0378
subtract 8352
x 8532
y 2358
subtract 6174
But what I get is actually this:
input:
3524
output:
x 5432
y 2345
subtract 3087
x 54325432
y 23452345
subtract 30873087
I think the problem is something with the x and y. I have to reset them to zero at some point. But I don't know where. I've tried every single place in the code. If anyone knows where I do wrong I will really appreciate the help.
The program fails for multiple reasons:
You do not reset x and y to 0 for each iteration
result should also be reset to 1
The initial phase of the loop is too complicated: you should test if substract is 0 or 6174 to stop the loop and store substract to number at the end of the loop.
Here is a simpler version that does not need to make number have 4 digits:
#include <stdio.h>
int main(void) {
int number;
if (scanf("%d", &number) == 1 && number >= 0 && number < 10000) {
for (;;) {
int x = 0, y = 0, substract;
for (int i = 9, j = 0; i >= 0 && j <= 9; i--, j++) {
for (int tmp = number, n = 0; n < 4; n++) {
int digit = tmp % 10;
if (digit == i) {
x *= 10;
x += digit;
} else
if (digit == j) {
y *= 10;
y += digit;
}
tmp /= 10;
}
}
substract = x - y;
printf("x %d\n", x);
printf("y %d\n", y);
printf("substract %d\n", substract);
if (substract == 0 || substract == 6174)
break;
number = substract;
}
}
return 0;
}
Related
In line 10 I cannot find out where my problem is at first. I place int a[100][100]={0} but the cpu speed is stuck.
Then, I try to change it into a[n][n] but no output is shown.
Last, I try to change it again as if it resembles the original ones.
However, nothing works instead of a new question.
#include<stdio.h>
int main() {
int n;
while (scanf("%d", &n)) {
n *= 2;
int x = 0, y = 0, num = 1;
int a[n][n] = {0};
a[x][y] = num++;
while (n * n >= num) //定義陣列
{
while (y + 1 < n && !a[x][y + 1]) //向右
a[x][++y] = num++;
while (x + 1 < n && !a[x + 1][y]) //向下
a[++x][y] = num++;
while (y - 1 >= 0 && !a[x][y - 1]) //向左
a[x][--y] = num++;
while (x - 1 >= 0 && !a[x - 1][y]) //向上
a[--x][y] = num++;
}
for (x = 0; x < n; x++) //print 陣列
{
for (y = 0; y < n; y++) {
if (y != n - 1) {
printf("%d ", a[x][y]);
} else {
printf("%d", a[x][y]);
}
}
printf("\n");
}
break;
}
return 0;
}
At least this problem:
Variable Length Arrays (VLA) cannot be initialized via the C standard.
Alternate, assign via memset() after defining a.
// int a[n][n]={0};
int a[n][n];
memset(a, 0, sizeof a);
I have a problem with a such a task:
Write a program that finds such a pair of numbers x and y that their sum is equal to n. In addition, the pair of numbers should meet the following conditions:
the number x has at least 2 digits,
the number y is one digit less than the number x.
N is from the range <10 ; 10^5>
for number 80, the output should look like this:
79 + 1 = 80
78 + 2 = 80
77 + 3 = 80
76 + 4 = 80
75 + 5 = 80
74 + 6 = 80
73 + 7 = 80
72 + 8 = 80
71 + 9 = 80
I wrote a code that works in most cases but the system rejects the solution when testing the number 100000, because the program does not find such pairs - the test requires 9000 such pairs. I can't understand what's wrong because I think the program is okay. I'd like to ask for some advice.
My code:
#include <stdio.h>
#include <math.h>
int digit_count(int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}
int breakdown(int n)
{
long n_digits = digit_count(n), check = 0, count = 1;
long double y_max = pow(10, (n_digits - 1)) - 1, y_min = (pow(10, (n_digits - 2)));
for (int i = (int)y_min; i <= (int)y_max; i++)
{
if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - 1))
{
printf("%d + %d = %d %d\n", n - i, i, n, count);
check = 1;
count++;
}
}
if (check == 0)
{
printf("Nothing to show.");
}
return 0;
}
int main(void)
{
unsigned int n = 0;
printf("Podaj N: ");
if (1 != scanf("%u", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
breakdown(n);
return 0;
}
PS: I forgot to mention that the count variable is here only for debugging
I solved the problem in this way. Now it works for all numbers in the range according to the task.
#include <stdio.h>
#include <math.h>
int digit_count(int n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i;
}
int breakdown(int n)
{
int n_digits = digit_count(n), check = 0;
double y_max = pow(10, n_digits - 1) - 1;
//int i = 0 instead of i = y_min = (pow(10, (n_digits - 2))
for (int i = 0; i <= (int)y_max; i++)
{
//instead of if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - i))
if (digit_count(n - i) >= 2 && digit_count(n - i) == digit_count(i) + 1)
{
printf("%d + %d = %d\n", n - i, i, n);
check = 1;
}
}
if (check == 0)
{
printf("Nothing to show.");
}
return 0;
}
int main(void)
{
unsigned int n = 0;
printf("Podaj N: ");
if (1 != scanf("%u", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
breakdown(n);
return 0;
}
The posted code checks all the numbers in [10k - 2, 10k - 1 - 1], k beeing the number of digits of n, using the expansive (and wrong) condition
if (digit_count(n - i) >= 2 && digit_count(i)+1 == digit_count(n - 1)) { /* ... */ }
// ^
You can solve the problem avoiding all (or at least most of) those digits counts, by carefully calculating the valid extents of the ranges of the x and y values.
The following is a possible implementation
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
static inline long min_(long a, long b)
{
return b < a ? b : a;
}
static inline long max_(long a, long b)
{
return b < a ? a : b;
}
int digit_count(long n);
// Specilization for integer exponent.
long pow_10_(int exponent);
// A little helper struct
typedef struct range_s
{
long begin, end;
} range_t;
// Shrinks the range of the y values so that all the x = z - y are valid
// (the right nummber of digits and less than z).
range_t find_range(long z, long x_0)
{
range_t y = {max_(1, x_0 / 10), x_0};
range_t x = {x_0, min_(z, x_0 * 10)};
long x_1 = z - y.begin;
if (x_1 < x.begin)
y.end = y.begin;
else if (x_1 >= x.end)
y.begin = min_(z - x.end + 1, y.end);
long x_2 = z - y.end;
if (x_2 > x.end)
y.begin = y.end;
else if (x_2 <= x.begin)
y.end = max_(z - x.begin + 1, y.begin);
return y;
}
long print_sums(long z, range_t y);
long breakdown(long z)
{
int n_digits = digit_count(z); // <- Only once.
long x_0 = pow_10_(n_digits - 1);
// Depending on z, the x values may have the same number of digits of z or
// one less.
long count = 0;
if (n_digits > 2)
{
count += print_sums(z, find_range(z, x_0 / 10));
}
count += print_sums(z, find_range(z, x_0));
return count;
}
int main(void)
{
long n = 0;
if (1 != scanf("%lu", &n))
{
printf("Incorrect input");
return 1;
}
if (n > 1000000 || n < 10)
{
printf("Incorrect input");
return 1;
}
printf("\nCount: %ld\n", breakdown(n));
return 0;
}
int digit_count(long n)
{
int i = 0;
while (n > 0)
{
n /= 10;
i++;
}
return i ? i : 1; // I consider 0 a 1-digit number.
}
long pow_10_(int exponent)
{
if (exponent < 0)
return 0;
long result = 1;
while (exponent-- > 0)
result *= 10;
return result;
}
#define SAMPLES 5
long print_sums(long z, range_t y)
{
for (long i = y.begin; i < y.end; ++i)
#ifndef SHOW_ONLY_SAMPLES
printf("%ld + %ld = %ld\n", z - i, i, z);
#else
if ( i < y.begin + SAMPLES - 1 || i > y.end - SAMPLES )
printf("%ld + %ld = %ld\n", z - i, i, z);
else if ( i == y.begin + SAMPLES )
puts("...");
#endif
return y.end - y.begin;
}
Testable here.
Write a program that examines three variables — x, y, and z — and
prints the largest odd number among them. If none of them are odd, it
should print a message to that effect.
This is my source code:
#include <stdio.h>
int main() {
int x,y,z;
x = 11;
y = 15;
z = 18;
if (x > y && x > z && x % 2 != 0)
printf("%d", x);
else if (y > z && y > x && y % 2 != 0)
printf("%d", y);
else if (z > x && z > y && z % 2 != 0)
printf("%d", z);
else
printf("error");
return 0;
}
The program is compiling and running but is giving the wrong answer. For the above it gives "error" as the output, but the greatest odd number is 15.
You are just printing the largest integer of the three if it is odd. For not to change you code so much and if you doesn't care about the others values, you can set the even variables to -INF. That is:
//INF can be whatever big even value you think that works fine (1e9), 0x3ffffffe, etc
#define INF 1e9
if (x % 2 == 0) x = -INF;
if (y % 2 == 0) y = -INF;
if (z % 2 == 0) z = -INF;
//here the rest of your code
In your example, y is the largest odd number, but it is not the largest number. z is larger, so "y>z" evaluates to false, and the path you want is not taken.
You may have noticed that your code is very repetitive. And the next exercise in the book is likely to be "OK, now do this for ten input numbers", which would be too tedious to contemplate, or "... for any number of input numbers", which just plain can't be done the way you're doing it.
So instead you should be thinking about a code structure like this:
int current_largest_odd_number = 0; /* note: zero is even */
for (;;) {
int n = read_a_number();
if (n == -1) break; /* read_a_number returns -1 on EOF */
if (is_even(n)) continue;
if (n > current_largest_odd_number)
current_largest_odd_number = n;
}
if (current_largest_odd_number > 0)
printf("largest odd number: %d\n", current_largest_odd_number);
The code is not printing the largest odd number, but is printing the largest number if it happens to be odd.
You need to keep track of the largest odd number you've found and then print that.
For example:
int found = false, largest = 0;
if (x%2 != 0) {
found = 1;
largest = x;
}
if (y%2 != 0) {
found = 1;
if (y > largest) {
largest = y;
}
}
if (z%2 != 0) {
found = 1;
if (z > largest) {
largest = z;
}
}
if (found) {
printf("%d", largest);
} else {
printf("error");
}
Your code prints the largest number if and only if is is odd.
You could instead test each number in turn and update a pointer to the maximum odd value if any.
#include <stdio.h>
int main() {
int x = 11;
int y = 15;
int z = 18;
int *largest = NULL;
if (x % 2 != 0) {
largest = &x;
}
if (y % 2 != 0) {
if (!largest || y > *largest) {
largest = &y;
}
}
if (z % 2 != 0) {
if (!largest || z > *largest) {
largest = &z;
}
}
if (largest) {
printf("%d\n", *largest);
} else {
printf("error\n");
}
return 0;
}
Here is an alternative approach with an indicator instead of a pointer:
#include <stdio.h>
int main() {
int x = 11;
int y = 15;
int z = 18;
int largest = 0;
int found = 0;
if (x % 2 != 0) {
largest = x;
found = 1;
}
if (y % 2 != 0) {
if (!found || y > largest) {
largest = y;
found = 1;
}
}
if (z % 2 != 0) {
if (!found || z > largest) {
largest = z;
found = 1;
}
}
if (found) {
printf("%d\n", largest);
} else {
printf("error\n");
}
return 0;
}
My version examines all possible three integer numbers and prints the largest
odd number (As an absolute beginner.)
x = int(input("number x = "))
y = int(input("number y = "))
z = int(input("number z = "))
/*Ask the user to input three variables*/
ans=0
if x%2==0 and y%2==0 and z%2==0:
print("There are no odd numbers.")
else:
if x<=y<=z and z%2!=0:
ans=z
elif y%2!=0:
ans=y
elif x%2!=0:
ans=x
if x<=y>=z and y%2!=0:
ans=y
elif x>=z and x%2!=0:
ans=x
elif z%2!=0:
ans=z
if x>=y<=z and x>=z and x%2!=0:
ans=x
elif z%2!=0:
ans=z
elif y%2!=0:
ans=y
if x>=y>=z and x%2!=0:
ans=x
elif y%2!=0:
ans=y
elif z%2!=0:
ans=z
print("The largest odd number is "+str(ans))
I have run this program and get the error expression result unused. I may be doing something simple wrong, but I have spent the day trying to figure it out to no avail. Any help you can provide is greatly appreciated.
#include <stdio.h>
#include <cs50.h>
int main()
{
int x, y = 0;
printf("Enter the amount of change ");
x = GetFloat() * 100;
while (x != 0)
{
if (x >= 25)
{
x - 25;
y = y + 1;
}
if (x >= 10 && x < 25)
{
x - 10;
} y = y + 1;
if (x >= 5 && x < 10)
{
x - 5;
} y = y + 1;
if (x >= 1 && x < 5)
{ x - 1;
y= y + 1;
}
}
printf("The number of coins neccessary is %d", y);
}
if (x >= 25)
{
x - 25; // This accomplishes nothing
y = y + 1;
}
if (x >= 10 && x < 25)
{
x - 10; // This accomplishes nothing
} y = y + 1;
if (x >= 5 && x < 10)
{
x - 5; // This accomplishes nothing
} y = y + 1;
if (x >= 1 && x < 5)
{
x - 1; // This accomplishes nothing
y= y + 1;
}
In each of those lines you're subtracting a number from x, but you're doing nothing with the result. If you're trying to update x with the result, you need to do just like you're doing with y, and put x = in front of the expression.
So if you want x to go down by 25, you should write:
x = x - 25;
Alternatively, you can write the shorthand:
x -= 25; // Note the equal sign
All the 4 statements x - 25, x- 10, x- 5, x - 1 will turn out to be useless unless you assign that value to x;
Because you are trying to subtract the value from x, but you are not assigning the new value to x.
Here is the solution of your problem:
#include <stdio.h>
#include <cs50.h>
int main()
{
int x, y = 0;
printf("Enter the amount of change ");
x = GetFloat() * 100;
while (x != 0)
{
if (x >= 25)
{
x = x - 25; //or x-=25;
y = y + 1;
}
if (x >= 10 && x < 25)
{
x = x - 10; //or x-=10;
y = y + 1;
}
if (x >= 5 && x < 10)
{
x = x - 5; //or x-=5;
y = y + 1;
}
if (x >= 1 && x < 5)
{
x = x - 1; //or x-=1; or x--; or --x; :)
y = y + 1;
}
}
printf("The number of coins neccessary is %d", y);
}
I would remain to be convinced about your loop structure. There's the division operator that can be used to good effect:
int total = 0;
int ncoins;
int amount = GetFloat() * 100;
assert(amount >= 0);
ncoins = amount / 25;
total += ncoins;
amount -= ncoins * 25;
assert(amount < 25);
ncoins = amount / 10;
total += ncoins;
amount -= ncoins * 10;
assert(amount < 10);
ncoins = amount / 5;
total += ncoins;
amount -= ncoins * 5;
assert(amount < 5);
total += amount;
That's written out longhand; you could devise a loop, too:
int values[] = { 25, 10, 5, 1 };
enum { N_VALUES = sizeof(values) / sizeof(values[0]) };
int total = 0;
int ncoins;
int amount = GetFloat() * 100;
assert(amount >= 0);
for (int i = 0; i < N_VALUES && amount > 0; i++)
{
ncoins = amount / values[i];
total += ncoins;
amount -= ncoins * values[i];
}
assert(amount == 0);
Write a program that will find the largest number smaller than N that is totally different from a given number X. One number is totally different from other only if it doesn't contain any of the digits from the other number. N and X are read from standard input. The problem should be solved without the use of arrays.
Example Input 1: 400 897
Example Output 1: 366
Example Input 2: 1000 1236498
Example Output 2:777
No it's not homework, it was on one of the midterms and it's been killing me. I though about taking the first numbers last digit with %10 then taking the second numbers digit with %10 comparing them but...I just can't get it to work...I ended up with an endless loop...I just don't understand how to get every digit of the numbers and compare them to the other number.
#include <stdio.h>
int main () {
int N, X, num_N, num_X, i, lastDigit_N, lastDigit_X, flag, smaller_than_N;
scanf("%d%d", &N, &X);
smaller_than_N = N - 1;
for (i = smaller_than_N; i > 0; i--) {
num_N = i;
num_X = X;
flag = 0;
while (num_N > 0) {
lastDigit_N = num_N % 10;
while (num_X > 0) {
lastDigit_X = num_X % 10;
if (lastDigit_N == lastDigit_X) {
break;
}
else {
flag = 1;
}
num_X /= 10;
}
num_N /= 10;
}
if(flag) {
printf("%d", i);
break;
}
}
return 0;
}
You could build a bitmask for your numbers showing the digits which are contained.
uint16_t num2bitmask(int number)
{
uint16_t result = 0;
while (number) {
int digit = number % 10;
number /= 10;
result |= (1 << digit);
}
return result;
}
With this function, you can create your bitmask for X and then iterate from N-1 down to 1 until you find a value which doesn't have any bits in common with the other value.
If you have a number with digits d_1, d_2, ..., d_n, and you're allowed to use digits in the set D, then possible solutions look like:
d_1, ..., d_{i-1}, max(d in D | d < d_i), max(d in D), ..., max(d in D).
That is, the digits are the same up to some point, then the next digit is as large as possible while being below the input digit, then the rest are just as large as possible.
Not all these "solutions" will be valid, but if you iterate through them in reverse order (there's exactly n for an input number of size n), the first valid one you find is the answer.
Some code, including tests:
#include <stdio.h>
int digit_length(int a) {
int r = 0;
while (a) {
a /= 10;
r += 1;
}
return r;
}
int get_digit(int a, int k) {
while (k--) a /= 10;
return a % 10;
}
int largest_different(int a, int b) {
int lena = digit_length(a);
int invalid = b ? 0 : 1;
for (; b; b /= 10) invalid |= 1 << (b % 10);
int max_valid = 9;
while (max_valid >= 0 && (invalid & (1 << max_valid)))
max_valid--;
if (max_valid == -1) return -1;
for (int i = 0; i < lena; i++) {
int d = get_digit(a, i) - 1;
while (d >= 0 && (invalid & (1 << d)))d--;
if (d < 0) continue;
int solution = 0;
for (int k = lena - 1; k >= 0; k--) {
solution *= 10;
solution += (k < i ? max_valid : k > i ? get_digit(a, k) : d);
}
return solution;
}
return -1;
}
int main(int argc, char *argv[]) {
struct {int n; int x; int want;} examples[] = {
{400, 897, 366},
{1000, 1236498, 777},
{998, 123, 997},
};
int error = 0;
for (int i = 0; i < sizeof(examples) / sizeof(*examples); i++) {
int got = largest_different(examples[i].n, examples[i].x);
if (got != examples[i].want) {
error = 1;
printf("largest_different(%d, %d) = %d, want %d\n",
examples[i].n, examples[i].x, got, examples[i].want);
}
}
return error;
}
There's not always a solution. In that case, the function returns -1.