For our activity today, we were tasked to make using recursion with the sum of digits. I already made this program:
int main()
{
int num = 0, sum;
printf("Enter an integer: ");
scanf("%d",&num);
//counter=1;
for ( sum=0; num>0;)
{
sum = sum + num % 10;
num = num /10;
}
printf("Sum = %d", sum);
getch();
return 0;
}
Our teacher added "Input and output must be done in the main() function." Am doing the right thing? Or am I missing something in my code?
To do recursion, create a function that recurses rather than using a for loop.
int SumDigits(int i) {
if (i < 10) {
return i;
}
else {
return i%10 + SumDigits(i/10);
}
}
scanf("%d", &i);
printf("%d\n", SumDigits(i));
What you have there is an iterative solution, not a recursive one.
Recursion involves defining the problems in terms of a simpler version of the problem, all the time working towards a fixed end point.
The fixed end point in this case is any number less than 10, for which the value is that digit.
The transition to a simpler case (for numbers greater than 9) is simply to add the least significant digit to the result of the number divided by ten (integer division).
Since it's classwork, pseudo-code only I'm afraid.
def digitSum (n):
if n < 10:
return n
return (n % 10) + digitSum (n / 10)
If you follow that for the number 314, you'll see what happens.
At recursion level one, n == 314 so it calculates 314 % 10 to get 4 and calls digitSum(31).
At recursion level two, n == 31 so it calculates 31 % 10 to get 1 and calls digitSum(3).
At recursion level three, n == 3 so it just returns 3
Back up to level two, that's added to the remembered 1 and returned as 4.
Back up to level one, that's added to the remembered 4 and returned as 8.
Hence you end up with the digit sum of 8 for the number 314.
Related
I am new to programming, and I have to make an assignment in C. I have to make a program that reads an integer n and outputs if it is divisible by 3. Unfortunately I am not allowed to use the % operator to check this. "A positive integer is divisible by 3 if and only if the sum of all its digits is divisible by 3." So the program must add the digits of n, and if this is larger then 9, I have to add the digits of this number etc, until the sum of the digits is equal to or less then 9. Because then I am allowed to say whether n is divisible by 3 or not. I also have to print the number of the lose digits each time. For example: input:9999-----output:9999 -> 36 -> 9. YES.
I made a loop:
while(n>9){
lastDigit = n%10;
sumDigits += lastDigit;
n = (n-lastDigit)/10;
}
sumDigits = sumDigits + n; /*this is the sum of the digits*/
Now if this is larger then 9, I have to enter this number in the loop again, but I don't know how to do this. I made 3 other loops with if else statements, but that way my program is way to long. How can I make my program shorter? Because some numbers have to go through the loop multiple times.
Thanks.
Niek
You need two loops here - one that will loop as long as n > 9 and another to loop over the digits of n and sum them:
int origN = n;
while (n > 9) {
int sum = 0;
int tmp = n;
while (tmp > 0) {
int lastDigit = n % 10;
sum += lastDigit;
tmp /= 10;
}
n = sum;
}
if (n == 3 || n == 6 || n == 9) {
printf("%d is divisible by 3\n", origN);
} else {
printf("%d is not divisible by 3\n", origN);
}
im writing a code which will show the result is to display the individual digits and the decimal equivalent.
For e.g., if n is 6 and the number entered is 110011, the printout will be
1 1 0 0 1 1
The decimal equivalent is 51
I have already sourced and edited a code, however it shows
"110011 110011 110011 110011 110011 110011" instead of
"1 1 0 0 1 1".
#include <math.h>
void main()
{
int num, binary, decimal = 0, base = 1, remainder, n, digits;
printf("Please enter the number of digits:\n");
scanf("%d", &n);
printf("Please enter the %d digits:\n",n);
scanf("%d", &num);
binary = num;
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
printf("%d ", binary);
n--;
}
printf("\nIts decimal equivalent is = %d \n", decimal);
}
The value in the variable binary becomes a copy of the value in the variable num in the following line.
binary = num;
Since it is never changed afterwards, it will always remain the same value, a copy of the value in num at the time when it was copied (see the code line above).
Your loop is executed n times (in your example six times).
Each time through the loop, the same copied value is printed in the following code line.
So the original value will be printed six times in your example.
printf("%d ", binary);
You did not actually ask a question (which is really recommended here at StackOverflow).
So I answered the question "Why is the same value printed six times?"
You probably want to now ask the next question, "How do get the desired result?"
That question is much harder to answer, because your code is quite far away from achieving that.
You would have to determine the binary digits one by one and in the right order.
You do determine the digits one by one, around the following line in your code.
remainder = num % 10;
But that is the wrong order, it gives you the digits from least signifying to most signifying. Try with an input of "100011" to see what I mean.
To be more precise I have to say that I guess that you want the digits from most to least, but maybe not, in that case it is easier: print remainder instead of binary.
If I am right and you do want most to least, then you have to make some way of reversing the digits. You could use a stack, an array, recursion or different (more complicated ) math involving to determine the number of digits first.
The reason you're getting this output is because each call for printf("%d ", binary); prints the entirety of the 'binary' variable onto the screen, and that variable contains the number as opposed to individual digits of that number.
The easiest way of accessing specific digits of a number is by first dividing it by some power of 10, then getting mod10 of that number, e.g.:
int number = 6543;
int lastDigit = number % 10;
int secondLastDigit = (number / 10) % 10;
int thirdLastDigit = (number / 100) % 10;
This works because dividing integers in C causes any fraction parts to be ommitted, thus if you divide 6543/10 (as in the example), you will not get 654.3, but 654.
You could create a function which will return a number's digit from any position like so:
int digitAt(int num, int pos)
{
// Divide num by 10^(pos - 1) to "shift" the number to the right
num /= pow(10, pos - 1);
// Return the last digit after the divisions
return num % 10;
}
The above function returns digits starting from the right (pos 1 = last digit, pos 2 = second last digit)!
To make this function more intuitive you could for example flip the number horizontally before dividing (123 becomes 321).
I went on a little tangent, back to the original topic. To achieve the functionality you want, you could write your code like this (just the while loop):
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
int binaryDigit = (binary / pow(10, n - 1)) % 10;
printf("%d ", binaryDigit);
n--;
}
Now, the reason you don't have to worry about your digits being read backwards (like in the previous function example) is because conveniently, your iterator, n, is already going in reverse direction ('from n to 0' as opposed to 'from 0 to n'), so you're reading the leftmost digits before the rightmost ones.
Hope that helped.
[EDIT] As pointed out in the replies, using pow() in integer operations may lead to undesired results. My bad. There are plenty of ways to achieve an integer power of 10 though, a function like
int powerOf10(int exp)
{
int num = 1;
while (exp > 0) {
num *= 10;
exp--;
}
return num;
}
should do the job.
The problem is that you do:
printf("%d ", binary);
but binary is the same value all the time, i.e. it's never changing so you get the original value printed again and again.
If you changed it to:
printf("%d ", remainder);
things would be "a bit better" as the binary pattern would be printed but in reversed order. So that's not the solution.
So instead you can collect the values in the loop and store them in a string to be printed after the loop. Like:
int main()
{
int num, decimal = 0, base = 1, remainder, n;
printf("Please enter the number of digits:\n");
scanf("%d", &n);
int idx = 2*n-1;
char *str = malloc(2*n); // Allocate memory for the string
str[idx--] = 0; // and zero-terminate it
printf("Please enter the %d digits:\n",n);
scanf("%d", &num);
while (n > 0)
{
remainder = num % 10;
decimal = decimal + remainder * base;
num = num / 10 ;
base = base * 2;
str[idx--] = '0' + remainder; // Put the "binary" (i.e. '0' or '1') char in the string
if (idx>0) str[idx--] = ' '; // Put a space in the string
n--;
}
printf("%s", str); // Print the string
printf("\nIts decimal equivalent is = %d \n", decimal);
free(str); // Free the string
return 0;
}
I wanna make a funcion that will take a natural number and make a new number so every digit in the old number will be incremented and if the digit is 9 it will become zero, but not to check specificly if the digit is 9.
example:
930 will return 41
9999 will return 0
879021 will return 980132.
This is what i got so far:
int newNumber(int n)
{
int dig;
if (n < 9)
return n + 1;
dig = n % 10;
dig++;
n = n / 10;
n = n * 10 + dig;
return newNumber(n/10);
}
There are a couple of issues with your code:
It doesn't handle a single digit of 9 (which cause a stack overflow).
Adding 1 to 9 makes 10 not 0.
I've run it through the sample data you supplied and it seems to work (in C#) and it has a hard core recursive line at the end.
int newNumber(int n)
{
if (n == 9)
return 0;
if (n < 9)
return n + 1;
return (newNumber(n / 10) * 10) + newNumber(n % 10);
}
Here's to avoid the check for n == 9:
int newNumber(int n)
{
static int table[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
return (n <= 9) ? table[n] : (newNumber(n / 10) * 10) + newNumber(n % 10);
}
A lookup table seems the most appropriate and does exactly what the requirements describe. Trying to use the non-compatible arithmetic operators results in side effects (as we see in Bathsheba's answer for example), that then need to be corrected.
unsigned newNumber(unsigned n, unsigned c = 0)
{
return n ? (n + 1) % 10 + 10 * newNumber(n / 10, 1 + c) : !c;
}
is one way, and it will treat 0 as 1, via the !c branch where c counts the number of recursions. Note the tail recursion in the ternary conditional branch - some compilers will optimise a tail recursion out to a simple loop, see What is tail recursion?
Bathsheba's solution posted above is very elegant by using the ternary operator, but it will give you a wrong result if the input is zero. To avoid that you may use a stub function:
#include <stdio.h>
int incDigits(int n)
{
return n ? (n + 1) % 10 + incDigits(n / 10) * 10 : 0;
}
int newNumber(int n)
{
return n ? incDigits(n) : 1;
}
int main()
{
for(int i = 0; i <= 100; ++i)
{
int n = newNumber(i);
printf("%d -> %d\n", i, n);
}
}
EDIT: user meaning-matters also posted a way to fix the input value problem using a lookup table, but he still has to check if n equals 9, which is something you don't want. So I believe using a stub function still is the best way.
Two ternary operator has been used to take care of the two cases:
i) number equal to 9
ii) number not equal to 9 => Another ternary operator is used to take care of further two possible cases:
a) number greater than 9( return sum of num(n/10)*10 and num(n%10) ); this can be further elaborated based on the argument fed to the num function.
b)number smaller than 9(return number plus one(n+1))
Once this function is called from the main function with argument equal to the number to be transformed in the manner asked in the question, each call in line4 will undergo recursion until they pass the argument to the subsequent iteration less than or equal to 9(which leads to termination of the recursion). With basic understanding of recursion, the above para can easily be understood in context to the subroutine below.
Blockquote
int num(int n)//line1
{//line2
int t;//line3
t=(n==9?0:(n>9?num(n/10)*10+num(n%10):n+1));//line4
return t;/line5
}//line6
Blockquote
So, I am trying to get this C code to work. It compiles, but produces incorrect outputs. It should list all pefect square numbers between 1 and a chosen value.
It is doing something wrong, and after alot of trial and error i think the issue is with the modulus operation...like its truncating early or doing some other strange thing.
// C Code
/*This program will identify all square numbers between one and a chosen integer*/
#include <stdio.h>
#include <math.h>
int main(){
int i, upper, square_int;
float square;
printf("This program will identify all square numbers between one and a chosen integer");
printf("Please enter the upper limit integer:");
scanf("%d", &upper);
upper = 13; /*scanf is the primary integer input method; this is here just to test it on codepad*/
for (i = 1; i<= upper; ++i) /*i want to run through all integers between 1 and the value of upper*/
{
square = sqrt(i); /* calc square root for each value of i */
square_int = square; /* change the root from float to int type*/
if (i % (int)square_int == 0) /*check if i divided by root leaves no remainder*/
printf("%d\n", i); /*print 'em*/
}
printf("This completes the list of perfect squares between 1 and %d",upper);
return 0; /*End program*/
}
The output on codepad is:
This program will identify all square numbers between one and a chosen integerPlease enter the upper limit integer:1
2
3
4
6
8
9
12
This completes the list of perfect squares between 1 and 13
Which is of course wrong. I expect to get 1, 2, 4 and 9 back. Can anyone point out my screw up here?
Here is a simpler algorithm
int i = 1;
while (i*i < upper)
{
printf("%d\n", i*i);
++i;
}
Another method is computing the square root, convert it to int, and compare the numbers.
for (i = 1; i <= upper; ++i)
{
square = sqrt(i);
square_int = square;
if (square == (float)square_int)
printf("%d\n", i );
}
Your modulo operation is incorrect. In case of i = 6 square_int will become 2 and thus i % (int)square_int is equal to 6 % 2 which leads to 0.
You could check if square_int * square_int == i instead.
You says you expect to get 1, 2, 4, 9 which means you don't expect to get 3.
Let's see with i == 3:
sqrt(3) == 1.732051
(int) 1.732051 == 1
3 % 1 == 0.
Which means it actually does what it is expected to do but it will not check if a number is a square.
A simple algorithm to check if the number is a square is to do:
sqrt_int = sqrt(i) + 0.5;
if (square_int * square_int == i)
printf("%d\n", i);
I'm writing a code in C that returns the number of times a positive integer can be expressed as sums of perfect squares of two positive integers.
R(n) is the number of couples (x,y) such that x² + y² = n where x, y, n are all
non negative integers.
To compute R(n), I need to first find the prime factorization of n.
The problem is that I've tried a lot of algorithm for prime factorization that I can use on C but I need my code to be as fast as possible, so I would appreciate it if anyone can give me what he/she considers as the fastest algorithm to compute the prime factorization of a number as large as 2147483742.
What an odd limit; 2147483742 = 2^31 + 94.
As others have pointed out, for a number this small trial division by primes is most likely fast enough. Only if it isn't, you could try Pollard's rho method:
/* WARNING! UNTESTED CODE! */
long rho(n, c) {
long t = 2;
long h = 2;
long d = 1;
while (d == 1) {
t = (t*t + c) % n;
h = (h*h + c) % n;
h = (h*h + c) % n;
d = gcd(t-h, n); }
if (d == n)
return rho(n, c+1);
return d;
}
Called as rho(n,1), this function returns a (possibly-composite) factor of n; put it in a loop and call it repeatedly if you want to find all the factors of n. You'll also need a primality checker; for your limit, a Rabin-Miller test with bases 2, 7 and 61 is proven accurate and reasonably fast. You can read more about programming with prime numbers at my blog.
But in any case, given such a small limit I think you are better off using trial division by primes. Anything else might be asymptotically faster but practically slower.
EDIT: This answer has received several recent upvotes, so I'm adding a simple program that does wheel factorization with a 2,3,5-wheel. Called as wheel(n), this program prints the factors of n in increasing order.
long wheel(long n) {
long ws[] = {1,2,2,4,2,4,2,4,6,2,6};
long f = 2; int w = 0;
while (f * f <= n) {
if (n % f == 0) {
printf("%ld\n", f);
n /= f;
} else {
f += ws[w];
w = (w == 10) ? 3 : (w+1);
}
}
printf("%ld\n", n);
return 0;
}
I discuss wheel factorization at my blog; the explanation is lengthy, so I won't repeat it here. For integers that fit in a long, it is unlikely that you will be able to significantly better the wheel function given above.
There's a fast way to cut down the number of candidates. This routine tries 2, then 3, then all the odd numbers not divisible by 3.
long mediumFactor(n)
{
if ((n % 2) == 0) return 2;
if ((n % 3) == 0) return 3;
try = 5;
inc = 2;
lim = sqrt(n);
while (try <= lim)
{
if ((n % try) == 0) return try;
try += inc;
inc = 6 - inc; // flip from 2 -> 4 -> 2
}
return 1; // n is prime
}
The alternation of inc between 2 and 4 is carefully aligned so that it skips all even numbers and numbers divisible by 3. For this case: 5 (+2) 7 (+4) 11 (+2) 13 (+4) 17
Trials stop at sqrt(n) because at least one factor must be at or below the square root. (If both factors were > sqrt(n) then the product of the factors would be greater than n.)
Number of tries is sqrt(m)/3, where m is the highest possible number in your series. For a limit of 2147483647, that yields a maximum of 15,448 divisions worst case (for a prime near 2147483647) including the 2 and 3 tests.
If the number is composite, total number of divisions is usually much less and will very rarely be more; even taking into account calling the routine repeatedly to get all the factors.