Is this example of recursion correct? - c

int main() {
int num;
printf("Enter a number\n");
scanf(" %d", &num);
num = prime(num);
if (num == 0)
printf("This is not a prime number");
if (num == 1)
printf("This is a prime number");
}
prime(int num) {
static i = 2;
if (num % i == 0)
return 0;
prime(i + 1);
return 1;
}
Note that it doesn't work in some compilers.
I want to know if we can call it recursion or not.
Specifically, I am confused if calling prime function like prime(i + 1) falls under recursion or not.

In your code your were passing i as argument in further recursive calls which was logically not correct. You need to pass the number as well as a divisor the function prime. The below code is one of the way to implement your logic.
#include<stdio.h>
int prime(int num,int i)
{
if(num==i)
return 1;
if(num % i == 0)
return 0;
return prime(num,i+1);
}
int main()
{
int num;
printf("Enter a number\n");
scanf(" %d", &num);
if(num>1){
num = prime(num,2);
if(num == 0)
printf("This is not a prime number");
else
printf("This is a prime number");
}
else printf("This is neither prime nor composite");
return 0;
}
Note the no input validation is performed and it is assumed that user will input only positive integers.

You are calling prime with i during the recursive call, which is not the actual value you want to check for prime, that is the reason it is not working!
It will return 0 for multiples of 2 only otherwise it will be stuck in an infinite loop.
int prime(int num) {
static i = 2;
if(num % i == 0)
return 0;
prime(i + 1); // passing i instead of num
return 1;
}
You can pass the divisor along with the number, and increase the divisor with 1 in every recursive call.
int prime(int num, int d) {
if(num == 0 || num == 1 || num % d == 0)
return 0;
if(d <= sqrt(num)) // num will not be divisible by d > sqrt(num)
prime(num, d + 1);
return 1;
}
Initially call prime with divisor 2 like prime(num, 2) in main.

Related

Why doesn't my code work for special cases?

I wrote up a piece of code to find whether a number is prime or not and here it is.
#include <stdio.h>
void main() {
int i, n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 3) {
printf("It is a prime number");
}
for (i = 2; i < n; i++) {
if (n % i == 0) {
printf("It's not prime number \n");
break;
} else {
printf("It is a prime number \n");
break;
}
}
}
However, when my input is 33, instead of the output printing It's not a prime number, since 33 is divisible by 3 and 11, it prints that It is a prime number.
What is the problem with my code here?
In your code, the first time the for loop is executed it immediately triggers either the if condition or else, then breaks, reaches the end and returns. The loop runs a total of 1 iteration max. Change to the following:
for (i = 2; i <= n / i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
Here the for runs correctly. It checks for all dividends, only then it's over and prints the false condition. Note you can optimize your code and only check up to the square root of n, because after that it can't hit true.
And add a return statement here, because the program is already over and doesn't need to continue:
if (n <= 1){
printf("It's not a prime number");
return 0;
}
if (n <= 3){
printf("It is a prime number");
return 0;
}
This also screens off 0, 1, and negative integers which are not prime numbers.
You almost got it right: you just have to make sure the program exits after having established whether a number is prime.
Also, you can stop the loop at n/i.
Last, but not least: main should return a int.
#include <stdio.h>
int main(void){
int i,n;
printf("Enter value for n: \n");
scanf("%d", &n);
if (n <= 3){
printf("It is a prime number\n");
return 0;
}
for (i = 2; i < n/i; i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("It is a prime number \n");
return 0;
}
There are multiple problems:
void main() should be int main()
you should check the return value of scanf and reject negative numbers
0 and 1 are not considered prime numbers.
you should end the program if the number matches the first test.
you output the result after a single test: it is correct if the test if (n % i == 0) is true as you have found a divisor, but if you have not, you should iterate, testing all possible divisors up to and including floor(sqrt(n)).
Here is a modified version:
#include <stdio.h>
int main() {
int i, n;
printf("Enter value for n: ");
if (scanf("%d", &n) != 1) {
printf("input error, not a number\n");
return 1;
}
if (n < 0) {
printf("number should be positive: %d\n", n);
return 1;
}
if (n <= 1) {
printf("%d is not a prime number\n", n);
return 0;
}
for (i = 2; i < n / i; i++) {
if (n % i == 0) {
printf("%d not prime number (divisible by %d)\n", n, i);
return 0;
}
}
printf("%d is a prime number\n", n);
return 0;
}
You might want to try this:
#include <bits/stdc++.h>
int main(){
int i,n;
printf("Enter value for n: ");
scanf("%d", &n);
if (n <= 1){
printf("It is a prime number");
}
for (i = 2; i <= sqrt(n); i++){
if (n % i == 0){
printf("It's not prime number \n");
return 0;
}
}
printf("A prime Number");
return 0;
}
This is happening because in your code for i = 3 and n = 33, if condition is failing which leads to else block directly and hence you are getting output as "It is a prime number".

Prime or perfect number program in C

I've made a program that checks if a given positive integer is a prime or perfect number.The problem I'm facing is I created a function "readNumber" that works as a check loop to ensure that input is a positive integer.But if I enter a negative value and then an acceptable one it shows previous values aswell.I attach a screenshot of the command prompt text to make myself more clear.
Below is my code
#include<stdio.h>
int checkperfectnumber(int);
int checkprimenumber(int);
int readNumber(int);
int main(){
int num, x, y, result;
printf("\nGive a positive integer number: \n");
scanf("%d",&num);
y = readNumber(num);
x = checkperfectnumber(num);
result = checkprimenumber(num);
if (num == 1)
printf("1 is nor a prime neither a perfect number");
else if (x == num)
printf("%d is a perfect number\n",num);
else if ( result == 1 )
printf("%d is a prime number.\n", num);
else
printf("%d is nor prime neither a perfect number.\n", num);
return 0;
}
//perfect number function
int checkperfectnumber(int numbr){
int a=1, sum=0;
while(a < numbr){
if(numbr % a == 0)
sum=sum+a;
a++;
}
return(sum);
}
//prime number function
int checkprimenumber(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}
//input check function
int readNumber(int b){
while (b < 0)
{
printf("Wrong input.\nPlease insert a positive integer.");
main();
break;
}
}
Quick fix is have the program exit after executing main() from readNumber().
To do this, Add #include <stdlib.h> and replace break; in the function readNumber() to exit(0);.
Better solution is having the function readNumber(), not main(), read numbers and stop calling main() recursively.
It will be like this:
#include<stdio.h>
int checkperfectnumber(int);
int checkprimenumber(int);
int readNumber(void);
int main(){
int num, x, y, result;
printf("\nGive a positive integer number: \n");
num = readNumber();
x = checkperfectnumber(num);
result = checkprimenumber(num);
if (num == 1)
printf("1 is nor a prime neither a perfect number");
else if (x == num)
printf("%d is a perfect number\n",num);
else if ( result == 1 )
printf("%d is a prime number.\n", num);
else
printf("%d is nor prime neither a perfect number.\n", num);
return 0;
}
//perfect number function
int checkperfectnumber(int numbr){
int a=1, sum=0;
while(a < numbr){
if(numbr % a == 0)
sum=sum+a;
a++;
}
return(sum);
}
//prime number function
int checkprimenumber(int a)
{
int c;
for ( c = 2 ; c <= a - 1 ; c++ )
{
if ( a%c == 0 )
return 0;
}
return 1;
}
//input check function
int readNumber(void){
for (;;)
{
int b;
scanf("%d",&b);
if (b >= 0) return b; /* 0 is not positive, but this condition is !(b < 0) */
printf("Wrong input.\nPlease insert a positive integer.");
}
}

School exercice in c about prime numbers

Make a program that asks the user for an integer and says if the
number is prime or not. A number greater than 1 is prime if only
is divisible by 1 and by itself. Then, it will tell us what the prime number is.
example:
Enter a number: 8
8 is not first. The first one immediately superior to 8 is 11.
Enter a number: 5
5 is first. The first one immediately above 5 is 7.
I can only solve first part.
Here is my code:
#include <stdio.h>
int main() {
int num, i;
do {
printf("Enter a numer: ");
scanf("%d", & num);
}
while (num < 1);
for (i = 2; i < num; i++) {
if (num % i == 0)
printf("Its prime");
}
if (num % 1 == 0 && num % num == 0)
printf("Not prime");
return 0;
}
Try this logic. Not tested
#include <stdio.h>
int main()
{
int num, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &num);
int isPrime=IsPrime(num)
if(isPrime==0){
numNext=num+1;
int nextPrimeNum=checkNextPrime(numNext);
}
}
int IsPrime(int num){
for(i = 2; i <= num/2; ++i)
{
// condition for nonprime number
if(num%i == 0)
{
flag = 1;
break;
}
}
if (num == 1)
{
flag=1;//neither prime nor composite
}
return flag;
}
int checkNextPrime(int numNext){
int isNextPrime=IsPrime(numNext)
if(isNextPrime==0){
printf("This is the required output :"numNext);
return numNext;
}
else{
numNext=numNext+1;
checkNextPrime(int numNext)
}
}

Program C counting total number of odd digits

I'm writing a C program that counts the number of odd digits from user input.
Eg.
Please enter the number: 12345
countOddDigits(): 3
int countOddDigits(int num);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int num)
{
int result = 0, n;
while(num != 0){
n = num % 10;
if(n % 2 != 0){
result++;
}
n /= 10;
}
return result;
}
The code is not working.
Can someone tell me where does it go wrong?
There were a few mistakes in your code. Here is a working version of your code:
#include <stdio.h>
int countOddDigits(int n);
int main()
{
int number;
printf("Please enter the number: \n");
scanf("%d", &number);
printf("countOddDigits(): %d\n", countOddDigits(number));
return 0;
}
int countOddDigits(int n)
{
int result = 0;
while(n != 0){
if(n % 2 != 0)
result++;
n /= 10;
}
return result;
}
You are mixing n and num together - there is no need for two variables.
n%=10 is just causing mistakes - you need to check the last digit if(n%2!=0) and then move to the next one n/=10, that's all.
Looping variable is not correct. Your outer loop is
while (num !=0)
but the num variable is never decremented; the final statement decrements the n variable. My guess is you want to initialize
int n = num;
while (n != 0 )
{ ...
n/= 10;
}

Prime Factorisation + prime number in C

Well I have been assigned to do the prime factorisation for composite numbers, but the problem is I have hard-coded it till prime numbers:2,3,5,7,11,13,19 and I want to make it general.
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void prime(int flag,int num);
int main()
{
int num, flag, i, div;
printf("Enter your number: ");
scanf("%d", &num);
flag = 1;
prime(flag, num);
printf("Press any key to exit.");
getchar();
return 0;
}
void prime(int flag, int num)
{
void factor(int num, int i);
int sq, i, square;
sq = abs(sqrt(num));
if (num == 2)
flag = 1;
else
for (i = 2; i <= sq; i++)
{
if (num % i == 0)
{
flag = 0;
break;
}
else
flag = 1;
}
if (flag == 1)
printf("\n%d is a prime number", num);
else
{
printf("\n%d is not a prime number\n", num);
factor(num, i);
}
}
void factor(int num, int i)
{
for (i = 2; i <= num; i++)
{
again:
if(num % i == 0)
{
num = num / i;
printf("%d x", i);
if (num != (2||3||5||7||11||17||19))
goto again;
}
}
printf("1\n\n");
}
P.S.:Try to make it as simpler as possible.
The problem is after dividing it with smallest prime. i.e. 2 the next step should be check the number whether it is a prime or not. If not, then factorise it but I dont know how to do it.
Plz help.
Thx in advance.
#include <stdio.h>
void factor(int num);
int main(void){
int num;
printf("Enter positive number(more than 1): ");
if(1 != scanf("%d", &num) || num < 2){
printf("invalid input!\n");
return -1;
}
scanf("%*[^\n]");scanf("%*c");//clear upto line end
factor(num);
printf("Press any key to exit...");
getchar();
return 0;
}
void factor(int num){
int i, flag = 0;
if(num == 2){
printf("\n%d is a prime number\n", num);
return ;
}
while(!(num & 1)){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("2 x ");
num >>= 1;
}
for (i = 3; i*i <= num; i += 2){
while(num % i == 0){
if(!flag)
printf("\n%d is not a prime number\n", num);
flag = 1;
printf("%d x ", i);
num /= i;
}
}
if(!flag)
printf("\n%d is a prime number\n", num);
else if(num != 1)
printf("%d x 1\n\n", num);
else
printf("1\n\n");
}
Replace line,
if (num!=2&& num!=3 && num!=5 && num!=7 && num!=11 && num!=17 && num!=19)
instead of,
if (num!=2||3||5||7||11||17||19)
In function factor, first try dividing by 2 repeatedly, then try every odd number while said odd number squared is less or equal to num. This simple method is a bit redundant as you try and divide by composite numbers, but since you will already have removed all smaller prime factors, num will not be divisible by such composite numbers. Iterating while i * i <= num will stop much earlier than with your current i <= num test.
Try and write code to implement the above algorithm and post it as an edit.

Resources