简体   繁体   中英

A simple recursion function prints weird stuff

So I need to code a recursive function that validates if the number is a prime number. The algorithm is pretty simple and works correctly, it's just that when I print the function rather than showing 1 or 0 it shows random crap (maybe addresses?) and I couldn't find out why.

The code:

int isPrimal(int n, int p) {
    if (p == 1) {
        return 1;
    }
    if (n % p == 0) {
        return 0;
    }
    isPrimal(n, p - 1);
    printf("n = %d i = %d\n", n, p);    
}

int main() {
    int numcase, *A, sizeA = 0, i = 0, cnt3dig = 0, n, p;

    printf("Enter a number to check for primality\n");
    scanf("%d", &n);
    p = (n - 1);
    printf("The result is 1 if the number is a prime, 0 otherwise\n");
    isPrimal(n, p);
    printf("The result is %d\n", isPrimal);
}

You are printing the address of the isPrimal() function, you should change it to

printf("The result is %d\n", isPrimal(n, p));

and don't forget to check scanf() 's return value.

The printf in main invokes undefined behavior because you pass the address of the function isPrimal instead of its result: change printf("The result is %d\\n", isPrimal); to

printf("The result is %d\n", isPrimal(n, p));

Furthermore, your algorithm is very inefficient. Function isPrimal calls itself recursively n-2 times. If you remove the printf statement, the compiler notices the tail call to itself and turns this recursion into a loop. When you have the printf statement it cannot do this and for large values of n you probably recurse too deep and cause a Stackoverflow .

There are 2 changes that are necessary 

1. In main, While printing the output make a function call -not a reference to the location of the function. 2. In isPrimal, Call the isprimal recursively after the print statement.

#include<stdio.h>
#include<stdlib.h>
  int isPrimal(int n, int p) {
    if (p == 1) {
        return 1;
    }
    if (n % p == 0) {
        return 0;
    }
    printf("n = %d i = %d\n", n, p);
    isPrimal(n, p - 1);
}

int main() {
    int numcase, *A, sizeA = 0, i = 0, cnt3dig = 0, n, p;

    printf("Enter a number to check for primality\n");
    scanf("%d", &n);
    p = (n - 1);
    printf("The result is 1 if the number is a prime, 0 otherwise\n");

    printf("The result is %d\n", isPrimal(n, p));
    return 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM