Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Solve the problem by recursion:
using three type coins include 1 yuan, 2 yuan and 5 yuan, plus to 10 yuan, how many combinations?
The following is my code :
int coinNum(int num){
if(num>=0){
if(num==0)
return 1;
else
return coinNum(num-5)+coinNum(num-2)+coinNum(num-1);
}else
return 0;
}
int main(){
int num=coinNum(10);
printf("%d\n",num);//the result is 128
system("pause");
return 0;
}
What's the error of my recursion algorithm or what's your right code ?question supplement :1. (5,2,2,1) and (2,5,2,1) should be counted as 1 combination . 2. the following is my code of the enumeration algorithm .
void coin(){
int i,j,k,count=0;
for(i=0;i<=10;i++)
for(j=0;j<=5;j++)
for(k=0;k<=2;k++)
if((i+2*j+5*k)==10){
count++;
printf("one yuan :%d,2 yuan :%d,5 yuan :%d\n",i,j,k);
}
printf("总方法数%d\n",count);//the result is 10
}
Your code is counting the number of permutations that add up to 10. You want combinations. That means (5,2,2,1) and (2,5,2,1) should be counted as 1 combination.
In this case, the answer should be 10: (5,5), (5,2,2,1), (5,2,1,1,1), (5,1,..1), (2,2,2,2,2), (2,2,2,2,1,1), (2,2,2,1,1,1,1), (2,2,1,..1), (2,1,..1), and (1,..1).
Try this code:
int coinNum(int num, int *coins){
if (num == 0) return 1;
if (num < 0 || !*coins) return 0;
return coinNum(num - *coins, coins) + coinNum(num, coins+1);
}
int main(){
int coins[] = {5,2,1,0}; // don't forget the 0 or the program won't end
int num=coinNum(10,coins);
printf("%d\n",num); // the result is 10
system("pause");
return 0;
}
The code above tries all combinations until the sum equals or exceeds the desired sum. Note that this is not the most efficient algorithm to solve this problem, but the most simple one. For better algorithms, you should probably look for it at Computer Science Stack Exchange.
Another simple algorithm, using idea to generate not decreasing sequence of coins.
int coinNum(int num, int min_coin) {
if (num == 0) {
return 1;
} else if (num < 0) {
return 0;
} else {
int res = coinNum(num - 5, 5);
if (min_coin <= 1) {
res += coinNum(num - 1, 1);
}
if (min_coin <= 2) {
res += coinNum(num - 2, 2);
}
return res;
}
}
int main(){
int num = coinNum(10, 1);
printf("%d\n", num);
return 0;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
Below is the program for my assignment. All of it was given except the printing and logic. I searched many videos about it and did what they did, but 15's binary is 1111 and the result was 0000
#include <stdio.h>
#include <math.h>
// Function to convert decimal to binary
// The function is void type so, print the result inside the function
void decimal2Binary(int dec) {
// array to store binary number
int binaryNumber[32];
// Your logic goes here
// fill out the binaryNumber
// i to increment the loop and terminate
int i = 0;
// We are interested in positive numbers for now
while (dec > 0) {
// Please add your logic to build the binary array
binaryNumber[i] = dec%2;
dec = dec/2;
i++;
}
// Print the binary array.
printf("Binary: ");
for (int j = i - 1; j >= 0; j--) {
printf("%d",binaryNumber[i]);
}
}
// The main function goes here
// The main function calls the decimal2Binary
int main() {
int decimal = 15;
printf("Decimal: %d equal to ", decimal);
decimal2Binary(decimal);
return 0;
}
DECIMAL TO BINARY (RECURSIVE):
#include <stdio.h>
int find(int dec_num)
{
if (dec_num == 0)
return 0;
else
return (dec_num % 2 + 10 *
find(dec_num / 2));
}
int main()
{
int decimal_number;
scanf("%d", &decimal_number);
printf("%d", find(decimal_number));
return 0;
}
DECIMAL TO BINARY (ITERATIVE):
#include <stdio.h>
long dec_to_bin(int decimalnum){
int binarynum = 0;
int mod, place = 1;
while(decimalnum != 0){
mod = decimalnum % 2;
decimalnum = decimalnum/2;
binarynum = binarynum + (mod*place);
place = place*10;
}
return binarynum;
}
int main() {
int decimalnum;
scanf("%d", &decimalnum);
printf("enter a decimal number:\n %ld", dec_to_bin(decimalnum));
return 0;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
This might be simple but I'm new to recursion in c. I want to find the sum of odd integers based on user's input. For example if user inputs 3, function returns 9 (1 + 3 + 5 = 9)
int recursiveSumNOdd(int n)
{
int start = -2; //later start = start+2, so it starts at 0
int n1 = n*2; //total number of digits with rec
int num = 0;
int sum=0;
int count=0;
if(start>=n1)
{
return 0;
}
else
{
start = start+2;
count++;
sum = sum +recursiveSumNOdd(start);
}
return sum;
}
Explanations in comment:
int recursiveSumNOdd(int n) {
if (n == 1 || n == 0)// first "if" in a recursive is its stop condition
return n;
return 2 * n - 1 + recursiveSumNOdd(n-1); // formula for 2->3, 3->5 etc
}
int main(void) {
printf("%d\n", recursiveSumNOdd(3));
return 0;
}
NB: You may want to handle integer overflow
NB2: You can have a mathematics formula to return instantly the result, it is way better, but I guess it was to understand better recursion?
return n * n; // the sum of odd numbers is the square of user's input
You are over-complicating things.
You cannot have the sum of negative elements.
int sum_n_odd(unsigned n)
{
What is the sum of 0 (zero) elements?
if (n == 0) return 0;
If you knew the sum of n - 1 numbers, what is the sum of n numbers?
return sum_n_odd(n - 1) + something; // something is easy to figure out
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
My question is how do I check if a digit is repeated in an integer without using arrays?
For example: 123145... 1 is repeated twice. so the output should be 15 (1+2+3+4+5)
My current code is:
# include "stdio.h"
int main () {
int input = 0;
int sum = 0;
int input = 0;
int sum = 0;
int digit;
printf("Please enter a number: ");
scanf("%d" ,&input);
while(input > 0) {
digit = input % 10;
if(d0 < 1) {
sum += digit;
d0 = 1;
}
input /= 10;
}
printf("Sum of different digits is: %d\n", sum);
return 0;
}
This is a really dumb way to solve this problem, but it uses neither arrays nor bit vectors:
#include <stdbool.h>
bool numberHasDigit(unsigned n, unsigned digit) {
while (n) {
if (n % 10 == digit) return true;
n /= 10;
}
return false;
}
unsigned sumOfUniqueDigits(unsigned n) {
unsigned sum = 0;
for (unsigned digit = 1; digit <= 9; ++digit) {
if (numberHasDigit(n, digit)) sum += digit;
}
return sum;
}
It's dumb because using an array (or bit vector) of flags is much faster, particularly for big numbers, and the code is just as simple:
unsigned sumOfUniqueDigits(unsigned n) {
bool seen[10] = {false};
unsigned sum = 0;
while (n) {
unsigned digit = n % 10;
if (!seen[digit]) {
sum += digit;
seen[digit] = true;
}
n = n / 10;
}
return sum;
}
I have avoided for loops and arrays and function calls.
Basically, we run a while loop that looks at the 9 interesting digits (1,2,3,4,5,6,7,8,9).
While looking at each digit, we run another while loop to see if the current digit is in the number by using your modulus and division looping. If the digit is in the number, then we add it to the sum.
We only look at each digit one time, so duplicates are ignored.
# include "stdio.h"
int main()
{
int input = 0;
int sum = 0;
printf("Please enter a number: ");
scanf("%d", &input);
//, now, subtract those values that do not exist in your number
int digit = 1; // start at 1, since 0 does not add to the sum
while (digit < 10) {
// check to see if the digit is in the number
int testInput = input;
while (testInput > 0) {
if (testInput % 10 == digit) {
sum += digit;
break; // Don't test for this digit any more, so go back to the outer loop.
}
testInput /= 10;
}
digit++; // increment the digit
}
printf("Sum of different digits is: %d\n", sum);
return 0;
}
A variation on the #rici good answer (and written as a one function call as #John Murray) with reduced operations - on average about 2x faster.
Rather than iterate 1 to 9, it looks for a repeat of the least significant digit in the rest of the number.
unsigned SumUniqueDigits(unsigned n) {
unsigned sum = 0;
while (n) {
unsigned lsdigit = n % 10;
n /= 10;
unsigned mssdigits = n;
while (mssdigits) {
if (mssdigits % 10 == lsdigit) {
lsdigit = 0;
break;
}
mssdigits /= 10;
}
sum += lsdigit;
}
return sum;
}
Alternative even faster: On re-examination - failed test code. Removed.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I'm receiving Output: 1. I should count the number of times a digit appear in an integer, for example, for number 1222345 and n = 2 Should appear 3 times.
int countOccurrences(int n, int num)
{
int i,k;
i=0;
while(num!=0)
{
k=num%10;
num=num/10;
if(k==n)
{
i++;
}
}
}
// Main
void main()
{
int num= 1222345;
int n = 2;
printf("Occurance of a number: %d", countOccurrences(n,num));
}
You have undefined behavior in the code. The function is supposed to return an int and it didn't.
Solution is to add return i in the end of other function. This will give you correct result. In the countOccurrences() function
...
if(k==n)
{
i++;
}
}
return i;
}
I was skipping the discussion of error check and all that. As chux mentioned for n<=0 case you might want to add a different way of handling it but you didn't add it. Atleast consider those case and put an error message on whatever input you need.
Some corner cases are
n=0,m=0.
Negative value of n or m.
Put a return on your countOccurrences function please
int countOccurrences (int n, int num) {
int i, k;
i = 0;
while (num! = 0)
{
k = num% 10;
num = num / 10;
if (k == n)
{
i ++;
}
}
return i; }
As other have pointed out, there are important issues with your code.
Here is a recursive solution that you may find interesting:
int countOccurrences(int n, int num)
{
int count = ((num % 10) == n);
return (num < 10) ? count : count + countOccurrences(n, num / 10);
}
Few general remarks about your code:
When using printf(), you should #include <stdio.h>.
main() should return int.
Place spaces around operators and format your code consistently. This k = num % 10; is more readable than k=num%10;. (There's more to code formatting than a matter of taste; without spaces you create areas full of characters which are more difficult to parse for our visual system.)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is the program I wrote. I get a blank output when I execute it. Can't figure out what's wrong with it.
#include <stdio.h>
void main() {
int a, b = 0, s, n;
printf("The armstrong numbers are-");
for (n = 1; n <= 10000; n++) {
s = n;
while (n > 0) {
a = n % 10;
b = b + a * a * a;
n = n / 10;
}
if (b == s)
printf("%d ", s);
}
}
As others have suggested Don't change n inside the for loop as your loop depends on the variable n. you have to set b back to 0 for each iteration.
Your program is not very much readable as others might not understand what does a,b,n and s mean. So, always use meaningful variable names like this: (see comments for more description)
#include<stdio.h>
int main(void) //correct signature for main function
{
int digit; //instead of a
int sum=0; //instead of b
int number; //instead of n
printf("The armstrong numbers are-");
for(number = 1; number <= 10000; number++)
{
int temporary = number; //temporary integer to store number value
sum = 0; //sum must be reset to 0 at the start of each iteration
while(temporary > 0)
{
digit = temporary % 10;
sum = sum + (digit * digit * digit);
temporary = temporary / 10;
}
if(sum == number) //if sum obtained == number, print it!
printf("%d ",number);
}
return 0;
}
output:
The armstrong numbers are-1 153 370 371 407
Don't change n inside the for loop.
you have to set b back to 0 for every n.
Hope I helped
The loop variable n was getting modified in the loop. So use the temporary variable s to do the inner while loop. And variable b must be initialized to zero every time you check for a new number. It's a good practice to define the variable within block that you use rather than defining everything globally or in the start of main.
#include <stdio.h>
int main() {
int n;
printf("The armstrong numbers are-");
for (n=1; n<=10000; n++) {
int a, b=0, s=n;
while (s > 0) {
a = s % 10;
b = b + (a*a*a);
s = s / 10;
}
if (b == n)
printf("%d ", n);
}
}