I am trying to find the persistence of a number. When you multiply the digits of a number together, eventually you will arrive at a single digit number. Persistence is the number of cycles that takes. I am trying to find that using a recursive Function. Here is my code:
#include <stdio.h>
int persistence(int x);
int main(int argc, char *argv[])
{
int x, per = 0, t;
char c;
while((c = getchar())!= EOF)
{
printf("Enter a number:\n");
scanf("%d", &x);
while(x>10)
{
t = persistence(x);
printf("\n%d", persistence(t));
per++;
}
printf("\n%d\n\n", per);
}
return 0;
}
int persistence(int x)
{
if(x<10)
{
return x;
}
else
{
return (x%10 * persistence(x/10));
}
}
The function persistence itself should return the value of the multiplicative persistence.
It can be defined the following way as it is shown in the demonstrative program.
#include <stdio.h>
size_t persistence( unsigned int x )
{
const unsigned int Base = 10;
if ( ! ( x < Base ) )
{
unsigned int n = 1;
do { n *= x % Base; } while ( x /= Base );
return 1 + persistence( n );
}
else
{
return 0;
}
}
int main(void)
{
unsigned int x = 39;
printf( "persistence( %u ) = %zu\n", x, persistence( x ) );
return 0;
}
The program output is
persistence( 39 ) = 3
Related
Been working on this question for class. Not sure what I'm doing wrong.
Seems like I just don't have the correct format. My professor wants the output to look like "5!=1 * 2* 3* 4* 5=120"
Can someone help me with this? Below is what I have so far:
#include <iostream>
#include <stdio.h>
int main() {
int n, i, fact;
printf("Enter a positive integer: \n");
scanf("%d", &n);
if (n < 0)
printf("Error! Factorial of a negative number doesn't exist.");
else {
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
printf("Factorial of %d = ", &n, &fact) ;
}
return 0;
}
remove #include <iostream> if it is the C code
Use functions.
Initialize local variables (you do not and it is undefined behaviour)
Compile C program using C compilers
unsigned long long fact(unsigned val, char *buff)
{
unsigned result = 1;
*buff++ = '1';
*buff = 0;
for(unsigned c = 2; c <= val; c++)
{
buff += sprintf(buff, "x%u", c);
result *= c;
}
return result;
}
int main(void)
{
unsigned x;
char y[1000];
unsigned long long res;
if(scanf("%u", &x) == 1){res = fact(x, y); printf("factoral(%u) = %s = %llu\n", x, y, res);}
else printf("Invalid number!!!\n");
}
or without printing steps
unsigned long long fact(unsigned val)
{
unsigned result;
switch(val)
{
case 0:
case 1:
result = 1;
break;
case 2:
result = 2;
break;
default:
result = 2;
while(val > 2) result *= val--;
break;
}
return result;
}
int main(void)
{
unsigned x;
if(scanf("%u", &x) == 1) printf("factioral(%u) = %llu\n", x, fact(x));
else printf("Invalid number!!!\n");
}
https://godbolt.org/z/Tf5431zco
For starters it does not make a sense to declare the variable n as having a signed integer type. It is better to declare it as having unsigned integer type. For example
unsigned int n, i, fact;
Secondly the variable fact was not initialized. You should initialize it by the value equal to 1.
So the above declaration could look like
unsigned int n, i;
unsigned long long fact = 1;
In this for loop
for( i = 1; i <= n; ++i) {
fact *= i;
n= n * (n-1);
}
the statement
n= n * (n-1);
does not make a sense and shall be removed.
In the printf call you have to use values of variables instead of pointers to the variables like
printf("Factorial of %u = %llu\n", n, fact) ;
Pay attention to that neither declaration from the header <iostream> is used in your program So whether it is a C program or a C++ program nevertheless remove this header.
Here is a demonstration C program.
#include <stdio.h>
int main( void )
{
unsigned int n = 0;
unsigned long long int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%u", &n );
printf( "%u! = ", n );
for ( unsigned int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%u", i );
}
printf( " = %llu\n", fact );
}
The program output might look like
Enter a positive integer: 5
5! = 1 * 2 * 3 * 4 * 5 = 120
If you are allowed to use only variables of the type int as you wrote in a comment to the answer then the program can look like
#include <stdio.h>
int main( void )
{
int n = 0;
int fact = 1;
printf( "Enter a positive integer: " );
scanf( "%d", &n );
if ( n < 0 )
{
puts( "Error! Factorial of a negative number doesn't exist.");
}
else
{
printf( "%d! = ", n );
for ( int i = 1; i <= n; i++ )
{
fact *= i;
if ( i != 1 ) printf( " * " );
printf( "%d", i );
}
printf( " = %d\n", fact );
}
}
To output multipliers in the reverse order like
5! = 5 * 4 * 3 * 2 * 1 = 120
rewrite the for loop the following way
for ( int i = n; i != 0; i-- )
{
fact *= i;
if ( i != n ) printf( " * " );
printf( "%d", i );
}
Using a while loop, i need count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.
input sample: 2, 124218
output sample: 2
this is my code below:
#include<stdio.h>
int main() {
int a;
int num;
int i;
int rev = 0;
int reminder;
int count = 1;
int ans;
int last;
scanf("%d",&a);
scanf("%d", &num );
while(num!=0)
{
reminder=num%10;
rev=rev*10+reminder;
num/=10;
if(a==reminder){
ans++;
last = ans%10;
printf("%d", last);
}
count++;
}
return 0;
}
int count_digit(const unsigned digit, int number)
{
int count = 0;
if(digit < 10)
{
while(number)
{
if(digit == abs(number % 10)) count++;
number /= 10;
}
}
else
{
count = -1; //error
}
return count;
}
int main(void)
{
printf("%d\n", count_digit(5, 455675));
printf("%d\n", count_digit(3, -35633435));
}
#include<stdio.h>
#include<stdlib.h>
int main() {
int a, num, remainder, count = 0;
scanf("%d",&a);
scanf("%d",&num );
int temp = abs(num);
while(temp!=0)
{
remainder=temp%10;
temp/=10;
if(a==remainder)
count++;
}
printf("%d",count);
return 0;
}
I am starter in the C.I wrote a simple code which are calculating how many digits are the entered Number and sum of entered number’s digits.Code calculating digit count right but sum of digits being given as ‘0’ every time.Could you say where is my error?thanks.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
int ndigit(int val) {
if (val == 0)
return 0;
int digit_count = 1;
while ((val = getchar() != '\n')) {
digit_count++;
val /= 10;
}
return digit_count;
}
int sumdigit(int number) {
int result = 0;
while ((number = getchar()) != '\n'){
result += number - '0';
}
return result;
}
int main()
{
int a;
printf("Bir tam sayi giriniz: \n");
a = getchar();
printf("Bu sayinin basamak sayisi =%d", ndigit(a));
printf("Bu sayinin basamak degeri toplami= %d", sumdigit(a));
}
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
The program does not make sense. To enter a number you should use one function. That is the number of digits and the sum of digits must be calculated for the same number.
This condition in the while statement
while ((val = getchar() != '\n')) {
is equivalent to
while ( ( val = ( getchar() != '\n' ) ) ) {
and as a result the integer val gets either 1 or 0.
As the variable val stores an internal representation of a character (for example its ASCII value) then this statement
val /= 10;
also does not make sense. Also the user can enter a non-digit character.
You should either use a character array for the entered number by means of calls of the function getchar or use the function scanf to enter a value of an integer object.
If to use a character array then the program can look the following way
#include <stdio.h>
char * get_number( char *number, size_t n )
{
size_t i = 0;
int c;
while( i + 1 < n && ( c = getchar() ) != EOF && c != '\n' && '0' <= c && c <= '9' )
{
number[i++] = c;
}
number[i] = '\0';
return number;
}
size_t ndigit( const char *number )
{
size_t n = 0;
while ( number[n] != '\0' ) ++n;
return n;
}
unsigned int sumdigit( const char *number )
{
unsigned int sum = 0;
while ( *number != '\0' )
{
sum += *number++ - '0';
}
return sum;
}
int main(void)
{
enum { N = 50 };
char number[N];
printf( "Bir tam sayi giriniz: " );
get_number( number, N );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look like
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
If to use an integer number then the program can look the following way
#include <stdio.h>
size_t ndigit( unsigned long long number )
{
const unsigned long long Base = 10;
size_t n = 0;
do
{
++n;
} while ( number /= Base );
return n;
}
unsigned int sumdigit( unsigned long long number )
{
const unsigned long long Base = 10;
unsigned int sum = 0;
do
{
sum += number % Base;
} while ( number /= Base );
return sum;
}
int main(void)
{
unsigned long long number = 0;
printf( "Bir tam sayi giriniz: " );
scanf( "%llu", &number );
printf( "Bu sayinin basamak sayisi = %zu\n", ndigit( number ) );
printf( "Bu sayinin basamak degeri toplami = %u\n", sumdigit( number ) );
return 0;
}
The program output might look as it is shown above.
Bir tam sayi giriniz: 123456789987654321
Bu sayinin basamak sayisi = 18
Bu sayinin basamak degeri toplami = 90
You code has 3 getchar() that are independent. Just use one getchar, either in main, or ndigit or sumdigit.
I propose, you should get the number in main function using scanf instead of getchar(), then pass the number as the argument to the other functions (ndigit and sumdigit). Because getchar reads character by character, and it does not guarantee the character is a digit or not.
The main function becomes:
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\n number of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
For two function ndigit and sumdigit, you can change to:
ndigit function:
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
num /= 10;
} while(num != 0);
return count;
}
sumdigit function:
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
The complete code:
#include <stdio.h>
#include <stdlib.h>
int ndigit(int number) {
number = abs(number); // calculate abs if the number is negative
if(number == 0)
return 1;
int count = 0;
do {
count++;
number /= 10;
} while(number != 0);
return count;
}
int sumdigit(int number) {
number = abs(number); // calculate abs if the number is negative
int sum = 0, temp = 0;
while (number != 0) {
temp = number % 10;
sum += temp;
number /= 10;
}
return sum;
}
int main () {
int num;
printf("enter the number: ");
scanf("%d", &num);
// calling the ndigit and sumdigit function:
printf("sum of digits = %d\nnumber of digits = %d\n", sumdigit(num), ndigit(num));
return 0;
}
The output of test:
enter the number: 222333
sum of digits = 15
number of digits = 6
After using scanf, change your sumdigit while loop to:
while (number > 0) {
result += number % 10;
number /= 10;
}
I'm curious why this code doesn't find the largest prime factor.
I can't find the mathematic and/or logic mistake.
#include <stdio.h>
int compute( int input ) {
int biggest_primefactor = 1;
while(input > biggest_primefactor) {
int i = 2;
while(input%i != 0) i++; /* find factor, which is a primefactor */
input /= i;
if( i > biggest_primefactor) biggest_primefactor = i;
}
return biggest_primefactor;
}
void main () {
unsigned long long int input = 600851475143;
printf("%d", compute( input ));
}
Output is 1
I am trying to use the following algorithm to convert a decimal number to a binary number in C. I don't understand why it doesn't work properly for some inputs (e.g. for 1993 I get 1420076519).
int aux=x;
long bin=0;
while (aux>0)
{
bin=bin*10+aux%2;
aux=aux/2;
}
printf("%d in decimal is %ld in binary.", x, bin);
When you print a long you dont print the binary. The best way to convert to binary or show the binary representation of a decimal number is by storing it in a string. Bellow is a solution offered in a another SO answer
void getBin(int num, char *str)
{
*(str+5) = '\0';
int mask = 0x10 << 1;
while(mask >>= 1)
*str++ = !!(mask & num) + '0';
}
If you know the algorithm there's no reason not to use itoa
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int n;
char output[100];
printf("Enter a number: ");
scanf("%d", &n);
itoa(n, output, 2); //2 means base two, you can put any other number here
printf("The number %d is %s in binary.", n, output);
return 0;
}
How does the conversion works?
/* Example:
125(10) -----> ?(2) 125 |_2
-1- 62 |_2
-0- 31 |_2
-1- 15 |_2
-1- 7 |_2
-1- 3 |_2
-1- 1 */
So in this example the binary number for 125(10) is 1111101(2), and this is the process I describe in my function.
/* Functions declaration (Prototype) */
int wordCalculator( int * const word, long int number, int base );
int main( void )
{
int i, base;
int word[ 32 ];
unsigned long int number;
printf( "Enter the decimal number to be converted: " );
scanf( "%ld", &number );
printf( "\nEnter the new base: " );
scanf( "%d", &base );
i = wordCalculator( word, number, base );
printf( "The number is: " );
for(; i >= 0; i--){
if ( word[ i ] <= 9)
printf( "%d", word[ i ] );
else
/* 65 represents A in ASCII code. */
printf( "%c", ( 65 - 10 + word[ i ] ) );
}
printf( "\n" );
}
int wordCalculator( int * const word, long int number, int base )
{
unsigned long int result = number;
int i, difference;
i = 0;
do{
difference = result % base;
result /= base;
*( word + i ) = difference;
i++;
if ( result < base )
*( word + i ) = result;
} while( result >= base );
return i;
}
I think the shortest answer is
char* getBinary(int n,char *s)
{
while(n>0)
{
*s=(n&1)+'0';
s++;
n>>=1;
}
*s='\0';
return s;
}
In the called function print it in reverse way .. because storing is done LSB to MSB
But we have to print MSB first then LSB
You should be using strings to store binary number. Following code should work for you.
#include <stdio.h>
#include <stdlib.h>
char *decimal_to_binary(int);
main()
{
int n, c, k;
char *pointer;
printf("Enter an integer in decimal number system\n");
scanf("%d",&n);
pointer = decimal_to_binary(n);
printf("Binary string of %d is: %s\n", n, pointer);
free(pointer);
return 0;
}
char *decimal_to_binary(int n)
{
int c, d, count;
char *pointer;
count = 0;
pointer = (char*)malloc(32+1);
if ( pointer == NULL )
exit(EXIT_FAILURE);
for ( c = 31 ; c >= 0 ; c-- )
{
d = n >> c;
if ( d & 1 )
*(pointer+count) = 1 + '0';
else
*(pointer+count) = 0 + '0';
count++;
}
*(pointer+count) = '\0';
return pointer;
}
You can use the below algorithm to convert Decimal number to Binary number system.
#include <stdio.h>
int main()
{
long long decimal, tempDecimal, binary;
int rem, place = 1;
binary = 0;
/*
* Reads decimal number from user
*/
printf("Enter any decimal number: ");
scanf("%lld", &decimal);
tempDecimal = decimal;
/*
* Converts the decimal number to binary number
*/
while(tempDecimal!=0)
{
rem = tempDecimal % 2;
binary = (rem * place) + binary;
tempDecimal /= 2;
place *= 10;
}
printf("\nDecimal number = %lld\n", decimal);
printf("Binary number = %lld", binary);
return 0;
}
This is a recursive solution that i wrote, it is simple and works fine.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int printBinary(int N)
{
if(N < 0){errno = EINVAL; return -1;}
if(N == 0)
printf("0");
else if(N == 1)
printf("1");
else
{
printBinary(N/2);
printf("%d", N%2);
}
return 0;
}
int main(int argc, char* argv[])
{
if(argc < 2)
{
fprintf(stderr, "usage: %s NUM\nWhere NUM is an integer number\n", argv[0]);
exit(EXIT_FAILURE);
}
errno = 0;
long NUM = strtol(argv[1], NULL, 10);
if(NUM == 0 && errno != 0)
{
perror("Error during number acquisition: ");
exit(EXIT_FAILURE);
}
if(NUM < 0)
{
printf("-");
printBinary(-NUM);
}
else
printBinary(NUM);
printf("\n");
return 0;
}