Why is my CheckFactorial script not working? [closed] - c

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 4 years ago.
Improve this question
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == factorial(number))
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac;
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
}
Why is this code not working?
My C code is meant for you to input a number and check if that number can be a factorial.
Like for example: if you enter 6 it should be Yes because 3! = 6 but if you enter 8 it would not work.
I d'ont think it's a duplicate because the method i did it was different.
Please note i'm not really good at C so any extra tips could be appreciated.

You need to correct 3 mistakes to make this program work.
You're comparing factorial of whichnumber with factorial of number that's wrong.
currnumber = factorial(whichnumber);
if (currnumber == factorial(number)) //<----never be true
{
return 1;
}
You should compare factorial of whichnumber with number
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
2 . You should initialize fac variable in factorial function otherwise it will take some garbage value.
int fac=1; //<-----initialize this variable
3. You should return the value of fact after calculating the factorial.
return fac; //<-----should return value
Here is the modified code:
#include <stdio.h>
int checkiffactorial();
int factorial(int n);
int number;
int main()
{
int answer, n, i;
printf("Enter a number: ");
scanf("%d", &number);
answer = checkiffactorial();
if (answer == 1)
{
printf("It's a factorial");
}
else
{
printf("It's not a factorial");
}
}
int checkiffactorial()
{
static int whichnumber = 1;
int currnumber;
if (whichnumber > number)
{
return 0;
}
if(whichnumber <= number)
{
currnumber = factorial(whichnumber);
if (currnumber == number) //<----should check whether it's same with the number
{
return 1;
}
whichnumber++;
checkiffactorial();
}
}
int factorial(int n)
{
int i;
int fac=1; //<-----initialize this variable
for(i=1; i<=n; ++i)
{
fac = fac * i;
}
return fac; //<-----should return value
}

It has been pointed out to you that you don't return value from your functions and use uninitialsed values. These errors are easy to make, but they are also easy to catch: Enable warnings for your compiler and they will tell you about these things.
Suvojit's answer tells you what is wrong with your factorial function. Unfortunately, more things are wrong with your factorial check:
You make the number you check a global variable. This should really be an argument to the function, so that you can call it like you should: is_factorial(n).
You make your counter a static variable. This is like a global variable, but with the restriction that it is only known in this function, which means that you cannot change it from outside. If your program want to check several numbers, the second call starts where you left off earlier, which leads to wrong results.
Of course that's what you want in your implementation, because you use a recursive algorithm. In this case, that's not a good choice; use a loop.
Your condition when to stop the iteration (or when to break the loop) checks the number against the number you took the factorial of. You should test this against the factorial itself.
Note that a typical int has 32 bits and can represent positive values up to 2³¹. The factorial 13! already exceeds this limit. So you must check your number against 12 values.
You don't need the factorial function for this, you can build these values as you go, because n! = (n − 1)! · n. (You can use the factorial function, but will do the same calculations over and over again, which is wasteful. It doesn't matter for this toy problem, but it is worth bearing such things in mind.)
So here's your function, completely rewritten:
int is_factorial(int n)
{
int fact = 1;
int k = 1;
while (k < 13 && fact <= n) {
fact *= k;
if (n == fact) return k;
k++;
}
return 0;
}
It returns 0 when the n isn't a factorial, otherwise it returns the number that n is a factorial of. (This information is used anyway, so why not provide it? The caller can choose whether to use this infor or just use it as truth value.)
While we're at it, let's adjust the main function so that the program checks for bad input and prints out the extra information we return:
int main(void)
{
int n;
printf("Enter a number: ");
if (scanf("%d", &n) < 1) {
printf("Illegal input!\n");
} else {
int m = is_factorial(n);
if (m) {
printf("%d is the factorial of %d!\n", n, m);
} else {
printf("%d is not a factorial!\n", n);
}
}
return 0;
}
The things to take away here are that you should use the compiler warning to tell you about simple errors, that you should avoid global and static variables for closed problems like these and that loops are often simpler than recursion.

Related

Write a C function that takes a number as a parameter and returns 1 if it is prime, otherwise, it returns 0. It prints 1 for 23 and 0 for 22 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 months ago.
Improve this question
I just want a 1 or 0 if it is prime or not.
but I am getting multiple 0's and 1's. How can I solve this.
#include <stdio.h>
int num() {
int a, i;
printf("Enter a number:");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
printf("1");
else
printf("0");
}
}
int main() {
num();
return 0;
}
Based on the naming used and specific combination of function use, I am almost certain OP's code is based off this which is my first google response to c check if number is prime.
I challenged myself to "fix" it with least number of modification to the original code, here is the version that works the way OP expects. It is ugly but the point is to make it clear where it differs from his code.
OP seems to have mixed up the inner if statements with the outer if statements, and completely forgot about the counter. Also OP seems to have got confused in the function num, as it should either print 1 or 0 and be a void function, or return 1 or 0 and take a as input to a function that returns int eg int num(int a) or void num(), whereas OP ended up going halfway int num().
The working(if you can call it that, since fflush(stdout) is not called after printf is called, so the program will not not show the question on mingw without winpty) program would look like this:
#include <stdio.h>
void num() {
// a is the user input number
// c is the count
// i is the iterator
int a, i, c = 0;
printf("Enter a number: ");
scanf("%d", &a);
for (i = 2; i < a; i++) {
if (a % i == 0)
++c;
}
if (c != 0)
printf("0");
else
printf("1");
}
int main() {
num();
return 0;
}
The reason you get multiple 0s and 1s is you print them for every potential factor. You should instead test the factors to determine if none of the factors up to the square root of the number divide the number evenly, printing a 1 in this case and a 0 otherwise.
Function isprime should take an int argument and return 1 or 0, the main() function takes case of getting the number from the user and printing the result.
Here is a modified version:
#include <stdio.h>
int isprime(int a) {
int i;
if (a < 2)
return 0;
for (i = 2; a / i >= i; i++) {
if (a % i == 0)
return 0;
}
return 1;
}
int main() {
int a;
printf("Enter a number:");
if (scanf("%d", &a) == 1) {
printf("%d\n", isprime(a));
}
return 0;
}
Also note how the code is indented and uses spaces to improve readability. Learn how to do this for your next projects.

i have a problem with my code and i'm not sure if i even wrote it correctly

so i'm practicing c and i built a program that says if its prime number or not and i tried to execute it but it wont work it doesnt shows me the output oh and im still new to this i started learning c one week ago.
i dont know how to fix this.
#include <stdio.h>
void Num();
int main()
{
void Num();
return 0;
}
void Num()
{
int n, i, flag = 0;
printf("Enter a num: ");
scanf("%d", &n);
for(i = 1; i <= 10; i++)
{
for(n = 1; n <= 10; n++)
{
flag = 1;
}
}
if( flag == 1)
{
printf("its not the prime num ");
} else{
printf("its the prime num" );
}
}
it wont even show the printf output
You need to go back to the basics (this means: reading a good C book before diving in). You are confusing declaration and calling of functions.
int main()
{
void Num();
return 0;
}
main contains two statements:
A local (re)declaration of Num as a function without return value.
A return statement.
Since you want to call Num rather than redeclaring it, you need to use the function call syntax:
int main()
{
Num();
return 0;
}
This is just the first step, however. Your Num function does not perform the correct actions to determine primality.

I have to find two smallest numbers without arrays [closed]

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 5 years ago.
Improve this question
So basicly I have this assignement in C, I have to input numbers until I enter 0, and after I enter 0 I have to print 1st and 2nd min number from all that numbers and I can't use arrays. I get that I have to use do-while loop for input but I can't figure out how to find two smallest from all of them. I think that thing can be done with if loops but don't know how to make it as I have only one variable to enter numbers into it (int a). And in input I have error when I enter 0 I'm able to enter one more number before program quits.
#include <stdio.h>
int main() {
int a;
do {
printf("Enter numbers: ");
scanf("%d\n", &a);
//what to do here
}while(a != 0);
You need to add 2 variables to hold the smallest values detected so far. Like
int smallest = INT_MAX;
int second_smallest = INT_MAX;
Then in the loop you need to test if the new input value is smaller than the values stored so far. Something like:
if (a <= smallest)
{
second_smallest = smallest;
smallest = a;
}
else if (a < second_smallest)
{
second_smallest = a;
}
You can use two variables to do what you need
#include <stdio.h>
#include <limits.h>
int main(void)
{
int a = INT_MAX;
int min_1 = INT_MAX;
int min_2 = INT_MAX;
int valid;
do
{
if (a < min_1)
{
min_2 = min_1;
min_1 = a;
}
else if (a < min_2)
{
min_2 = a;
}
printf("Enter numbers: ");
valid = scanf("%d", &a);
}
while ((a != 0) && (valid == 1));
if (valid == 1)
{
printf("Minimum numbers entered are: %d %d\n", min_1, min_2);
}
else
{
fprintf(stderr, "Error in data input\n");
}
}
So:
use limits.h defines to init min variables to the highest value for int type INT_MAX.
for each loop you must test if entered number is a minimum
you must check that user input is valid: check scanf return value.
remove \n in the format string of scanf.

Check if number is a power of two, and if the input is number [closed]

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 5 years ago.
Improve this question
I want to check if the numbers in an array are a power of two.
I wrote the following code, but it doesn't work it skips the part that checks if the number is the power of two and prints the last sentence.
Also, if someone can help me in how to check if the input is a number and not any other character.
Thank you!
update the power of two thing is working but i still haven't figure out how to check if the input is a number and not any other characher
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
int i;
int k;
int count=0;
int a;
int sum=0;
printf("Enter size of input:\n");
scanf("%d",&x);
int *numbers=malloc(sizeof(int)*x);
if (x<0){
printf("Invalid size\n");
}
else {
printf("Enter numbers:\n");
for(i=0;i<x;++i){
scanf("%d",&numbers[i]);
}
}
for(k=0;k<x;++k)
{
count=0;
a=numbers[k];
while (((numbers[k] % 2) == 0) && numbers[k] > 1){ /* While x is even and > 1 */
numbers[k]/= 2;
++count;
}
if (numbers[k]==1&&a!=1){
printf("The number %d is a power of 2:%d=2^%d\n",a,a,count);
sum+=count;
}
}
printf("Total exponent num is %d\n",sum);
return 0;
}
Your check for the power of two is wrong: you divide out two all the way down to 1, but the following if incorrectly checks numbers[k]==0.
The check should be numbers[k]==1 instead, because when you divide out all twos from a power of two you end up with 20, which is 1.
Note: You can check if a number is a power of two without a loop by using a bit trick described in this Q&A.
There's much in your example that's incidental to the problem. For example, allocating an array and reading user input is just a distraction from finding the solution. Concentrate first on debugging your algorithm:
#include <stdbool.h>
bool is_power_of_two(int n)
{
while (n % 2 == 0 && n > 1){ /* While x is even and > 1 */
n/= 2;
}
return n == 0;
}
int main()
{
return !is_power_of_two(2);
}
Now, you can refine that function until it gives the correct result. The simple fix is to replace n == 0 with n == 1. Now you can add more tests, running the program as you add each one:
int main()
{
return is_power_of_two(0)
+ !is_power_of_two(1)
+ !is_power_of_two(2)
+ is_power_of_two(3)
+ !is_power_of_two(4)
/* negative numbers can never be an exact power of a positive */
+ is_power_of_two(-1)
+ is_power_of_two(-2)
+ is_power_of_two(-3);
}
Once you have some confidence in your function, you can then use it in your program to process arrays.
When you do introduce a function to read input, you'll want to check that x isn't negative before using in the argument to malloc(). Better would be to ensure it's not negative, by using an unsigned type:
unsigned int x;
printf("Enter size of input:\n");
if (scanf("%u", &x) != 1) {
fprintf(stderr, "That's not a valid size!\n");
return EXIT_FAILURE;
}
int *numbers = malloc(x * sizeof *numbers);
if (!numbers) {
fprintf(stderr, "Couldn't allocate memory for %u numbers!\n", x);
return EXIT_FAILURE;
}

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr §6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}

Resources