"can you reverse the number" is the number already reverse by using Mod(%). My question, can it be reversed to normal?
For example, if you enter the number "2552" it'll change to "2+5+5+2", which is correct, but, when you enter another number like "4125" it will change to "5+2+1+4" instead of "4+1+2+5"
Ok, I just entered the programming world, a newcomer
With the "if" can it add "+" without exceeding the number like "4+1+2+5+"
there are "+" after "5", how can I delete this extra "+"?
#include <stdio.h>
main(){
int a, b, h=0;
printf("Enter the number : ");
scanf("%d",&a);
printf("%d = ", a);
while(a != 0)
{
b=a%10;
a=a/10;
printf("%d",b);
if(b != a)
{
printf("+");
}
h=h+b;
}
printf(" = %d\n", h);
}
Instead of scanning for an actual number, you can scan a string from the user. Strings are easy to reverse:
char num[5]; // Has the input
char rev[5]; // Will have the reverse
int len = strlen(num);
rev[len] = 0; // End the string
for(int i = 0; i < len; i++){
rev[i] = num[len-i-1];
}
You can go backwards by taking the highest digits in your number first instead of the lowest, e.g. like so:
int currentLog10;
int powerOfTenForCurrentDigit;
...
while(a != 0)
{
currentLog10 = (int)log10(a);
powerOfTenForCurrentDigit = (int)pow(10, currentLog10);
b = a/powerOfTenForCurrentDigit;
a = a - b * powerOfTenForCurrentDigit;
...
}
How does it work:
log10 of 4125 will give us 3.
b is set to 4125 devided by 1000 (10^3) = 4.
a is set to 4125 - 4 * 1000 = 125
Next step log10 of 125 gives 2, we devide by 10^2 (100) and so on.
Last step 5 gives 0, 5 devided by 10^0 (1) gives 5, a becomes 5 - 5 * 1, which is 0, we are done.
You have to be careful in edge cases, where log10 returns something like (n-1).999999999 instead of n, but it shouldn't happen for small numbers as are entered in your program. Maybe add some sanity check for the input.
Related
I am doing an assignment for my class but I am stuck. The assignment is to:
Write a recursive program to precompute Fibonacci numbers and store them in an array. Fibonacci formula is Fib(0) = 1, Fib(1) = 1 and Fib(i) = Fib(i − 1) + Fib(i − 2). Store the ith Fibonacci number at index i. Have a loop to read i and print i and ith Fibonacci number. Use −1 to quit the loop. My output is wrong but I don't know how to fix it. I have been trying for a while now but I just couldn't pinpoint my mistake.
My code is
#include <stdio.h>
double Fib[50]; //globally declared
int fib(int i)
{
for(i=0; i<50; i++) //loop to scan
{
scanf("%lf", &Fib[i]); //scan and store numbers in an array
if (Fib[i]==-1) //i =-1 will end loop
break;
}
Fib[i]= Fib[i-1]+Fib[i-2];//formula
if(Fib[i]==0||Fib[i]==1) //i=0 and i=1 will print 1
Fib[i]=1;
else if(i>1) //performs the operation with the formula
printf("%d %lf\n", i, Fib[i]);
}
int main()
{
int i=0;
fib(i);
return 0;
}
Expected result:
user input: 4 10 20 15 5 -1
output:
4 5.000000
10 89.000000
20 10946.000000
15 987.000000
5 8.000000
My output:
5 20.000000
A couple points:
Your program isn't recursive
Compute all of Fib first with your recursive function then after
handle user input in a loop
The code below has the structure for dealing with user input, do the recursion:
#include <stdio.h>
// It would make sense for this to store unsigned long long instead of double
// because Fibonacci numbers are always positive integers
unsigned long long Fib[50];
// Your assignment specifically said use a recursive program to compute Fib.
// This is not a recursive function, but it is correct, I will leave the
// recursion for you to work out
void populateFib() {
Fib[0] = 1;
Fib[1] = 1;
unsigned i;
for (i = 2; i < 50; ++i)
Fib[i] = Fib[i - 1] + Fib[i - 2];
}
int main() {
// First compute Fib
populateFib();
// Deal with user input in an infinite loop
for (;;) {
int input;
scanf("%d", &input);
// Condition for breaking the infinite loop
if (input == -1)
break;
// Sanity check the user won't read out of bounds
if (input < 0 || input >= 50) {
printf("No!\n");
continue;
}
// Display what the user wants
printf("%d %llu\n", input, Fib[input]);
}
return 0;
}
Hello guys i am trying to implement a program which is finding the happy numbers were between two numbers A and B.
Summing the squares of all the digits of the number, we replace the number with the outcome, and repeat the process. If after some steps the result is equal to 1 (and stay there), then we say that the number N is **<happy>**. Conversely, if the process is repeated indefinitely without ever showing the number 1, then we say that the number N is **<sad>**.
For example, the number 7 is happy because the procedure described above leads to the following steps: 7, 49, 97, 130, 10, 1, 1, 1 ... Conversely, the number 42 is sad because the process leads to a infinite sequence 42, 20, 4, 16, 37, 58, 89, 145, 42, 20, 4, 16, 37 ...
I try this right down but i am getting either segm faults or no results.
Thanks in advance.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void happy( char * A, int n);
int numPlaces (long n);
int main(void)
{
long A,B;
int npA;
char *Ap;
printf("Give 2 Numbers\n");
scanf("%li %li",&A,&B);
npA = numPlaces(A);
Ap = malloc(npA);
printf("%ld %d\n",A,npA);
//Search for happy numbers from A to B
do{
sprintf(Ap, "%ld", A);
happy(Ap,npA);
A++;
if ( npA < numPlaces(A) )
{
npA++;
Ap = realloc(Ap, npA);
}
}while( A <= B);
}
//Finds happy numbers
void happy( char * A, int n)
{
//Basic Condition
if ( n == 1)
{
if (A[0] == 1 || A[0] == 7)
printf("%c\n",A[0]);
printf("%s\n",A);
return;
}
long sum = 0 ;
char * sumA;
int nsum;
int Ai;
//Sum the squares of the current number
for(int i = 0 ; i < n;i++)
{
Ai = atoi(&A[i]);
sum = sum + (Ai*Ai);
}
nsum = numPlaces (sum);
sumA = malloc(nsum);
sprintf(sumA, "%li", sum);
happy(sumA,nsum);
free(sumA);
}
//Count digits of a number
int numPlaces (long n)
{
if (n < 0) return 0;
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
Thanks for your time.
by the definition of your program sad numbers will cause your program to run forever
Conversely, if the process is repeated indefinitely
You need to add a stopping condition, like if I have looped for 1000 times, or if you hit a well known non terminating number (like 4) (is there a definite list of these? I dont know)
I find this solution tested and working..
Thanks for your time and I am sorry for my vagueness.
Every advice about this solution would be welcome
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void happy( char * A, int n);
int numPlaces (long n);
int happynum = 0;
int main(void)
{
long A,B;
int npA;
char *Ap;
printf("Give 2 Numbers\n");
scanf("%li %li",&A,&B);
npA = numPlaces(A);
Ap = malloc(npA);
//Search for happy numbers from A to B
do{
sprintf(Ap, "%ld", A);
happy(Ap,npA);
if (happynum ==1)
printf("%s\n",Ap);
A++;
if ( npA < numPlaces(A) )
{
npA++;
Ap = realloc(Ap, npA);
}
}while( A <= B);
}
//Finds happy numbers
void happy( char * A, int n)
{
//Basic Condition
if ( n == 1)
{
if (A[0] == '3' || A[0] == '6' || A[0] == '9')
{
happynum = 0;
}
else
{
happynum = 1;
}
return;
}
long sum = 0;
char * sumA;
int nsum;
int Ai;
//Sum the squares of the current number
for(int i = 0 ; i < n;i++)
{
Ai = (int)(A[i]-48);
sum = sum + (Ai*Ai);
}
nsum = numPlaces (sum);
sumA = malloc(nsum);
sprintf(sumA, "%li", sum);
happy(sumA,nsum);
free(sumA);
}
//Count digits of a number
int numPlaces (long n)
{
if (n < 0) return 0;
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
Your code uses some questionable practices. Yoe may be misguided because you are concerned about performance and memory usage.
When you allocate memory for the string, you forget to allocate one character for the null terminator. But you shouldn't be allocating, re-allocating and freeing constantly anyway. Dynamic memory allocation is expensive compared to your other operations.
Your limits are long, which may be a 32-bit or 64-bit signed integer, depending on your platform. The maximum number that can be represented with e 64-bit signed integer is 9,223,372,036,854,775,807. This is a number with 19 digits. Add one for the null terminator and one for a possible minus sign, so that overflow won't hurt, you and use a buffer of 21 chars on the stack.
You probably shouldn't be using strings inthe first place. Use the basic code to extract the digits: Split off the digit by taking the remainder of a division by 10. Then divide by 10 until you get zero. (And if you use strings with a fixed buffer size, as described above, you don't have to calculate the difits separately: sprintf returns the number of characters written to the string.
Your functions shouldn't be recursive. A loop is enough. As pm100 has noted, you need a termination criterion: You must keep track of the numbers that you have already visited. Each recursive call creates a new state; it is easier to keep an array, that can be repeatedly looked at in a loop. When you see a number that you have already seen (other than 1, of course), your number is sad.
Happy and sad numbers have this property that when your sum of squares is a number with a known happiness, the original number has this happiness, too. If you visit a known das number, the original number is sad. If you visit a known happy number, the original number is happy.
The limits of your ranges may ba large, but the sum of square digits is not large; it can be at most the number of digits times 81. In particular:
type max. number number of max. square sum dss
int 2,147,483,647 1,999,999,999 730
uint 4,294,967,295 3,999,999,999 738
long 9,223,372,036,854,775,807 8,999,999,999,999,999,999 1522
ulong 18,446,744,073,709,55,1616 9,999,999,999,999,999,999 1539
That means that when you take the sum of digit squares of an unsigned long, you will get a number that is smaller than 1540. Create an array of 1540 entries and mark all known happy numbers with 1. Then you can reduce your problem to taking the sum of digit squares once and then looking up the happiness of the number in this array.
(You can do the precalculation of the array once when you start the program.)
so I want to create a code that finds the quantity of numbers in a number. So this may sound weird, but it works something like this.
Input
12893012
Output
1 2 2 1 0 0 0 0 1 1
So the output means that in 12893012, there is one 0, two 1's, two 2's, one 3, no 4, no 5, no 6, no 7, one 8, and one 9.
#include <stdio.h>
int main()
{
int n,count=0;
printf("Enter an integer: ");
scanf("%d", &n);
while(n!=0)
{
n/=10; /* n=n/10 */
++count;
}
printf("Number of digits: %d",count);
}
My code only seems to find the number of digits in the number, any ideas? Thanks a lot btw.
Put it in an array and count.
Roughly,
int count[10] = {0};
while(n != 0)
{
count[n % 10]++;
n /= 10;
}
Print out the result.
You keep incrementing count but without checking the digit. This will just give you the number of digits. You need an array in which you can store the count for each digit.
int digitCounts[10];
//...
while (n != 0){
digitCounts[n % 10]++;
n /= 10;
}
You can use mod (%) to make it easier, because % 10 gives the last digit.
Make an array that stores the digit count. Remainder operator will give you the last digit which will be between 0 and 9.
int digit[10];
//...
while(n!=0)
{
int d = n % 10;
digit[d]++
//...
And then print it in a loop.
I suggest creating an array (or 10 variables) which hold quantitiy of digits, then reading digits one by one and checking what digit it is.
You can read single digit using
scanf(%1d, &variableName)
or
getchar()
functions.
all thanks go to #rohit89,#this and #Arc676
this is just a correction when zero (0) is entered
int count[10] = {0};
if(n){
while(n != 0)
{
count[n % 10]++;
n /= 10;
}
}else
count[0]=1;
I'm trying to solve a problem from the book programming challenges by Skiena and when submitted to the online judge, one solution passed while the other one failed.
I'm trying to understand why one is an acceptable answer and the other is not. The only difference seems that one uses a separate method while the other does not. In which test would the second solution fail?
problem goes as follows:
The 3n + 1 problem
Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n, terminating when n = 1. For example, the following sequence of numbers will be generated for n = 22:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured (but not yet proven) that this algorithm will terminate at n = 1 for every integer n. Still, the conjecture holds for all integers up to at least 1, 000, 000.
For an input n, the cycle-length of n is the number of numbers generated up to and including the 1. In the example above, the cycle length of 22 is 16. Given any two numbers i and j, you are to determine the maximum cycle length over all numbers between i and j, including both endpoints.
Input
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
Output
For each pair of input integers i and j, output i, j in the same order in which they appeared in the input and then the maximum cycle length for integers between and including i and j. These three numbers should be separated by one space, with all three numbers on one line and with one line of output for each line of input.
Sample Input
1 10
100 200
201 210
900 1000
Sample Output
1 10 20
100 200 125
201 210 89
900 1000 174
The acceptable solution is as follows:
#include <stdio.h>
int cylen(int n){
int count = 1;
while (n !=1 ){
if (n%2 == 0)
n = n/2;
else
n = 3*n +1;
++count;
}
return count;
}
int maxcylen(int s, int e){
int tmp,i,maxcy, sz;
if(s>e){
tmp =s;
s = e;
e = tmp;
}
maxcy = 0;
for(i=s;i<=e;i++){
sz = cylen(i);
if (sz> maxcy)
maxcy =sz;
}
return maxcy;
}
int main(){
int s,e;
while(scanf("%d %d", &s, &e) != EOF){
printf("%d %d %d\n",s,e,maxcylen(s,e));
}
return 0;
}
The unacceptable one is as follows:
#include <stdio.h>
int cylen(int n){
int count = 1;
while (n !=1 ){
if (n%2 == 0)
n = n/2;
else
n = 3*n +1;
++count;
}
return count;
}
int main(){
int s,e, tmp,i,maxcy, sz;
while(scanf("%d %d", &s, &e) != EOF){
if(s>e){
tmp =s;
s = e;
e = tmp;
}
maxcy = 0;
for(i=s;i<=e;i++){
sz = cylen(i);
if (sz> maxcy)
maxcy =sz;
}
printf("%d %d %d\n",s,e,maxcy);
}
return 0;
}
in first solution you have two variables s and e which are defined in main function and two separate variables s and e which are defined only in maxcylen function
these variables are totally different ones
in first solution you're modifying s and e, but only inside function, so during output of result old ones from main are displayed, and this is right solution
to fix second solution, you need to do this:
int s,e, tmp,i,maxcy, sz, originalS, originalE; // note 2 additional variables
while(scanf("%d %d", &s, &e) != EOF){
originalS = s; // storing of values from file
originalE = e;
if(s>e){
tmp =s;
s = e;
e = tmp;
}
maxcy = 0;
for(i=s;i<=e;i++){
sz = cylen(i);
if (sz> maxcy)
maxcy =sz;
}
printf("%d %d %d\n",originalS,originalE,maxcy); // output of variables from file, instead of modified ones
}
Here are two functions below that compile perfectly but I seem to be getting a weird error with the very first inputted integer. I have tried debugging in GDB but when it's only the first inputted value that is having this weird error, then it makes things complicated.
#include <stdio.h>
#include "Assg9.h"
#include <stdlib.h>
#include <assert.h>
#include <math.h>
void getPrimes(int usernum, int* count, int** array){
(*count) = (usernum - 1);
int sieve[usernum-1], primenums = 0, index, fillnum, multiple;
for(index = 0, fillnum = 2; fillnum <= usernum; index++, fillnum++){
sieve[index] = fillnum;
}
for (; primenums < sqrt(usernum); primenums++)
{
if (sieve[primenums] != 0){
for (multiple = primenums + (sieve[primenums]); multiple < usernum - 1; multiple += sieve[primenums])//If it is not crossed out it starts deleting its multiples.
{
if(sieve[multiple]) {
--(*count);
sieve[multiple] = 0;
}
}
}
}
int k;
for (k = 0; k < usernum; k++)
if (sieve[k] != 0)
{
printf("%d ", sieve[k]);
}
*array = malloc(sizeof(int) * (usernum +1));
assert(array);
(*array) = sieve;
}
void writeToOutputFile(FILE *fpout, const int *array, int n, int count){
int i;
fprintf(fpout, "There are %d prime numbers less than or equal to %d \n", count, n);
for(i = 0; i < count; i++)
{
if(*(array + i) != 0){
fprintf(fpout, "%d ", *(array + i));
}
}
}
Our Output:
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2 32664
Do you want to try again? Press Y for Yes and N for No: y
Please enter an integer in the range 2 <-> 2000 both inclusive: 2
2
Do you want to try again? Press Y for Yes and N for No: n
Good bye. Have a nice day
Expected output should obviously just display 2. This is the case for any integer from 2-2000 for the very first inputted integer. The very last, or last 2, prime numbers print very large numbers, sometimes even negative numbers. I have no clue why, but after the first inputted value everything works perfectly. Tried debugging this with GDB like crazy but with no luck. Would really appreciate someone's help for this bizarre error
You aren't initializing the sieves array to 0s. So you're looping from 0 to usernum-1, printing out every number that isn't a 0. Since you didn't initialize the array, the 2nd element is a random value and is being printed out
This code is a problem:
(*array) = sieve;
You are are assigning the address of sieve, a temporary local array, to *array. You need to copy the array contents instead.
Are you also this person who has asked three questions about identical code?