Question: can u write this simple 'Cprogram'? write a program that generates prime number's from 1 to 500 using the concept of recursive function.

Answer: This is recursive only. The comments explain what is done.\n\n#include <stdio.h>\n\n// check if n is divisible by d\n// and call recursively for d-1 downto 1\nint testPrime(int n, int d) {\n    // numbers < 1 aren't prime, abort recursion then\n    if(d<2) return 1;\n    // not divisible by d? then continue testing\n    if(n % d != 0) return testPrime(n, d-1);\n    // else return 0, e. g. n isn't prime\n    return 0;\n}\n\n// n is prime, if not divisible by n/2 ... 2\nint isPrime(int n) {\n    return testPrime(n, n >> 1);\n}\n\n// print all primes <= n\nvoid printPrimes(int n) {\n    // 2 is the smallest prime --> no recursion for n=2\n    if(n==2) { printf("2 "); return; }\n    // recursion: print all primes < n\n    printPrimes(n-1);\n    // n is prime? then print it\n    if(isPrime(n)) printf("%d ", n);\n}\n\nint main() {\n    printPrimes(500);\n    printf("&#92;n");\n    return 0;\n}
This question from the Yahoo Q&A forum is categorized in the topic: Society & Culture