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
}
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 3 years ago.
Improve this question
I tried this problem using for loop but i did not got the correct output as specified . i do not know what is the problem in my code ?
#include <stdio.h>
int main()
{
int T,N;
scanf("%d %d" ,&T,&N);
for(int i=N;i>0;i=i/10)
{
int r=N%10;
int sum=0;
sum=sum+r;
printf("The sum is : %d" ,sum);
}
}
The sum is : 5The sum is : 5The sum is : 5The sum is : 5The sum is : 5
The output is coming like this while we just need sum of digits printed
for(int i = N; i > 0 ; i = i/10)
{
int r = N % 10; // calculating remainder of UNMODIFIED input, so will
// ALWAYS be last digit
int sum = 0; // you are initializing the sum to 0 for every single iteration
sum = sum + r; // so this will *always* result in 0 + N % 10
printf("The sum is : %d", sum);
}
To fix, you need to initialise the sum just once to collect all of the single digits. Additionally, you need to use the modified value:
int sum = 0;
for(int i = N; i > 0 ; i = i/10)
{
int r = i % 10;
// ^ (!)
sum += r; // alternative variant...
printf("The sum is : %d\n", sum);
// ^^ for better output formatting
}
Until now we are still printing the sum with every iteration as well. That might be useful, if you want to follow how the sum evolves (assuming input was 1210):
The sum is 0
The sum is 1
The sum is 3
The sum is 4
But actually, you'd rather want to print only the result, wouldn't you? So you'd move the printing out of the loop as well:
for(...)
{
...
}
printf("The sum is : %d\n", sum);
Alternative variant: If you don't need the value of N afterwards any more anyway, you can iterate directly on it:
for( ; N > 0; N /= 10)
// ^ empty initialization, nothing to be done...
{
int r = N % 10; // NOW using N is fine...
...
}
Finally: if you compare with != instead of >, you can cover negative intput (as you use signed integers...) as well.
Edit according to question:
it asked input and output like this. Input 3 12345 31203 2123 Output 15 9 8
Well, in this case, you need a double loop:
int t;
// well, actually, you should check if you did get correct input:
if(scanf("%d", &t) != 1))
{
// invalid input
// appropriate error handling, e. g. printing a message and:
return -1;
}
for( ; t > 0; --t) // handles the number of tasks to solve
{
int n; // inside loop: read in a new value with every task
scanf("%d", &n); // TODO: check input, see above
int sum = 0;
for(...) { ... } // loop handling the input value, see above
printf(...);
}
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 5 years ago.
Improve this question
I do the sum of the digits like that:
while(number>0)
{
sum+=number%TEN;
number=number/TEN;
}
but I need that if the number is (for example) 123444 so it'll include only one 4 in the sum. how can I do that?
Have an array of all digits initialized to zero
int digits[10] = { 0 };
Then before adding a digit you check if digits[that_digit] is zero, if yes you set it to 1 and add to sum, if no keep going ...
while(number>0)
{
int one = number%TEN;
if ( ! digits[one]) {
sum+=one;
digits[one] = 1;
}
number=number/TEN;
}
Edit, no array version
Add an int initialized to 0, the bit i indicates if that digit i has already been summed.
If 1 was added, bit 1 set to 1, if 2, bit 2 set to 1 etc...
int bits = 0;
while(number>0)
{
int one = number%TEN;
if (!(bits & (1<<one))) {
sum+=one;
bits |= 1<<one;
}
number=number/TEN;
}
First you should put some code here whatever you tried, to give you basic idea to solve your problem I am putting simple code below.
#include<stdio.h>
#include<malloc.h>
int main()
{
int input, digit, temp, sum = 0;
printf("Enter Input Number :\n");
scanf("%d",&input);
temp = input;
//first find how many digits are there
for(digit = 0 ; temp != 0 ;digit++, temp /= 10);
//create one array equal to no of digits, use dynamic array because once you find different digits you can re-allocate memory and save some memory
int *p = malloc(digit * sizeof(int));
//now store all the digits in dynamic array
p[0] = input % 10;//1
for(int i = 0; i < digit ;i++) {
input /= 10;
p[i+1] = input %10;
if(p[i] != p[i+1])
sum = sum + p[i];
}
printf("sum of different digits : = %d \n",sum);
free(p);
p = 0;
return 0;
}
Explanation of this code I mentioned in comments itself, it may not work for all test case, remaining try yourself.
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;
}
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 8 years ago.
Improve this question
Imagine we've got an int number = 1040 or int number = 105 in a C program, and we want to know if this number contains a 0 and in which position/s are they. How could we do it?
Examples
1040 -> position 0 and 2.
1000 -> position 0, 1 and 2.
104 -> position 1.
56 -> NO ZEROS.
Thanks!
I would divide by 10 and check the remainder. If remainder is 0, then last position of the number is 0. Then repeat the same step until number is less than 10
#include<iostream>
int main(void)
{
long int k = 6050404;
int iter = 0;
while (k > 10) {
long int r = k % 10;
if( r == 0) {
std::cout << iter << " ";
}
k = k / 10;
iter++;
}
}
I would convert it to a string; finding a character in a string is trivial.
As a rule of thumb, if you are doing maths on something, it's a number; otherwise, it's probably (or should be treated as) a string.
Alternatively, something like:
#include <stdio.h>
int main(void) {
int input=1040;
int digitindex;
for (digitindex=0; input>0; digitindex++) {
if (input%10==0) {
printf("0 in position %i\n",digitindex);
}
input/=10;
}
return 0;
}
This basically reports if the LAST digit is 0, then removes the last digit; repeat until there is nothing left. Minor modifications would be required for negative numbers.
You can play with this at http://ideone.com/oEyD7N
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 8 years ago.
Improve this question
I'm having trouble with arrays. I copied this code from a book:
#include <stdio.h>
#include <stdbool.h>
int main (void)
{
int p, i, primes[50], primeIndex = 2;
bool isPrime;
primes[0] = 2;
primes[1] = 3;
for (p = 5; p <= 50; p = p + 2) {
isPrime = true;
for (i = 1; isPrime && p / primes[i] >= primes[i]; ++i)
if (p % primes[i] == 0)
isPrime = false;
if (isPrime == true) {
primes[primeIndex] = p;
++primeIndex;
}
}
for (i = 0; i < primeIndex; ++i)
printf ("%i ", primes[i]);
printf ("\n");
return 0;
}
In particular, I'm having trouble understanding the difference between the primeIndex and the i variables. The primeIndex refers to the array number and i refers to the number placed into the array. Right?
primeIndex is the place where the next found prime is written in the prime array, and also the number of primes known so far. i is the index of the prime used for trial division. For each candidate, i loops from 1 (we don't need to try out primes[0] = 2 because only odd numbers are checked) to the index of the first prime larger than the square root of the candidate.