Prime or perfect number program in C - 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.");
}
}

Related

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)
}
}

Is this example of recursion correct?

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.

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.

Is this code correct for checking for prime number in c using functions?

Is this code correct for checking prime number using functions. I am not getting any syntax errors but it is always showing prime regardless of what I enter.
#include<stdio.h>
int prime(int);
void main() {
int n, count, a;
printf("enter the number\n");
scanf("%d", &n);
prime(n);
if (count == 2)
printf("prime");
else
printf("not prime");
}
int prime(int n) {
int i, count = 0;
for (i = 1; i <= n; i++) {
if (n % i == 0) {
count++;
}
return (count);
}
}
Modify your function prime -
int prime(int n) {
int i, count = 0;
for (i = 1; i <n; i++) { // go till n (or better till sqrt of n)
if (n % i == 0) {
count++;
}
if(count==2){ // if count is 2 get out of loop
break;
}
}
return count; // return out of loop
}
In you function main-
1. void main -> int main(void)
2. write you if else satatements as follows -
if (count == 2)
printf("not prime");
else
printf("prime");
3. initialize count to 0 in main.
call function as -
count=prime(n);
Your prime function doesn't work properly. In the first for loop you're doing n & 1 == 0 which always is true, and in the last loop n % n == 0 also is always true
int prime(int n){
int i;
int isPrime = 1;
for(i=2;i<sqrt(n) && isPrime;i++){ // do the loop while 2<i<sqrt(n) and n isPrime, once you know it's not prime don't loop anymore
isPrime = n%i; // If it's 0 then it's not prime (isPrime = 0) else it's true
}
return isPrime;
}
Edit: Optimized the for loop until i=sqrt(n)
/* i just needed to take input of value count and store it in a variable*/
#include<stdio.h>
int prime(int);
int main(void)
{
int n,count,a,m;
printf("enter the number\n");
scanf("%d",&n);
m=prime(n);
if(m>2)
printf("not prime");
else
printf("prime");
}
int prime(int n)
{
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
return(count);
}
A simple function return true if the number is prime and false if not.
int prime(int n){
int i;
for(i= 2; i < n; i++){
if(n % i ==0 && i != n)
return true;
}
return false;
}

recursive func to find prime factors

i made a recursive function to find the prime factors of a number but it has a bug which makes turbo c quit. please help
#include<stdio.h>
#include<conio.h>
int prime(int num);
int primefactor(int num,int i);
void main(void)
{
int num;
printf("Enter a number whose prime factors are to be calculated:");
scanf("%d",&num);
primefactor(num,i);
i=num
getch();
}
int primefactor(int num,int i)
{
if(i==2)
return 1;
if(num%i==0)
{
if(prime(num))
{
printf(",%d",num);
num=num/i;
i++;
}
}
i--;
primefactor(num,i);
return 0;
}
int prime(int num)
{
int i,flag;
for(i=2;i<num;i++)
{
if(num%i==0)
flag=0;
}
return flag;
}
void main(void)
{
int num,i=num; // (*)
printf("Enter a number whose prime factors are to be calculated:");
scanf("%d",&num);
primefactor(num,i);
getch();
}
What value do you think i will have in (*)?
Not sure what you want i to start out as, but I'm pretty sure you don't want it to be something random. If you want it to start with the value of num, you need to assign num to it after you read it:
void main(void)
{
int num,i;
printf("Enter a number whose prime factors are to be calculated:");
scanf("%d",&num);
i = num; // assignment goes here.
primefactor(num,i);
getch();
}
(little too sleepy to write good code.. so am sorry in advance for any bugs :p )
a simpler non recursive version
printPrimeFactors(int num) {
for (i = 2; i < sqrt(num); i=getNextPrime()) {
if (num %i)
printf("%d", i);
}
}
if you have to use recursion
void factorization(int x, int i=2)
{
if(x==1)
return;
if(x%i==0&&isPrime(i))
{
printf("%d ",i);
factorization(x/i,i);
}
else
factorization(x,i+1);
}
Full recursive solution in c++ (for c replace cout lines with printf):
void printPrimeFactors(int num)
{
static int divisor = 2; // 2 is the first prime number
if ( num == 1 ) //if num = 1 we finished
{
divisor = 2; //restore divisor, so it'll be ready for the next run
return;
}
else if ( num % divisor == 0 ) //if num divided by divisor
{
cout << divisor << " "; //print divisor
printPrimeFactors( num / divisor ); //call the function with num/divisor
}
else //if num not divided by divisor
{
divisor++; //increase divisor
printPrimeFactors( num );
}
}
The best way to implement prime factorization with low overhead function calls would be . . .
void factors(int number)
{
int divisor = 2;
if (number == 1) { cout << "1"; return; }
while ((number % divisor) && (number > divisor)) divisor++;
cout << divisor << ", ";
factors(number / divisor);
}
The number of function calls (recursion) is equal to the number of prime factors, including 1.
I did this in C. Depending on the compiler, minor changes might be needed to make in the program.
#include<stdio.h>
int primefact(int);
int main()
{
int n;
printf("Enter a number whose prime factors are to be calculated : \n");
scanf_s("%d", &n);
printf("Prime factors of %d are : ");
primefact(n);
printf("\n");
return 0;
}
int primefact(int n)
{
int i=2;
while(n%i!=0)
i++;
printf("%d ", i);
if(n==i)
return 0;
else
primefact(n/i);
}
Agree with IVlad - also, what happens in the case when num is prime? How many times will the recursive function be called for e.g. num = 7?
#include<stdio.h>
#include<stdlib.h>
int ar[10]={0};
int i=0,j=2;
void P(int n)
{
if(n<=1){
return ;
}
else{
if(n%j == 0){
printf("%d\t",j);
n=n/j;
}
else{
j++;
}
P(n);
}
}
int main(void)
{
int n;
printf("Enter n = ");
scanf("%d",&n);
P(n);
printf("\n");
return 0;
}
// recursivePrime.cpp
// Purpose: factor finding for an integer
// Author: Ping-Sung Liao, Kaohsiung,TAIWAN
// Date: 2017/02/02
// Version : 1.0
// Reference:
// http://stackoverflow.com/questions/3221156/recursive-func-to-find-prime-factors
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int primefactor(int num,int i);
int main(void)
{
int num, i;
printf("Enter a number whose prime factors are to be calculated:");
scanf("%d",&num);
i=int ( sqrt (num) );
primefactor(num,i);
system("pause"); // instead of getch()
}
int primefactor(int num,int i)
{ printf("num %d i=%d\n", num, i);
if (i==1)
printf("prime found= %d\n", num); // prime appearing in he variuable num
else if(num%i==0)
{ primefactor( int (num/i) , int ( sqrt(num/i) ) );
primefactor( i , int (sqrt ( i ) ) );
}
else
{ i--;
primefactor(num,i);
}
return 0;
}
#include <`stdio.h`>
void pf(int,int);
int main()
{
int a,i=2;
printf("Enter the Number:\n");
scanf("%d",&a);
pf(a,i);
}
void pf(int x,int y)
{
if(x==1)
return 1;
else
{
if(x%y==0)
{printf("%d\t",y);
pf(x/y,y);
}
else
{
y++;
pf(x,y);
}
}
}
We need not write function to calculate next prime number. If for example, num is 24 and we continously divide it by 2 until it is no longer divisible by 2, then no other multiples of 2 can divide the number either. So ultimately only(probably) prime numbers can perfectly divide any positive integer number.
Here is my code: (I've written source code for both iterative as well as recursive logic)
#include<stdio.h>
void pfactors_rec(int, int);
void pfactors(int);
int main()
{
int num;
printf("Enter a positive integer number\n");
scanf("%d", &num);
printf("\nPrime Factors of %d without using recursion\n", num);
pfactors(num);
printf("\nPrime Factors of %d using recursion\n", num);
pfactors_rec(num, 2);
return 0;
}
void pfactors_rec(int num, int count)
{
if(num < 1)
return;
else if(num % count == 0)
{
printf("%d\n", count);
pfactors_rec(num / count, count);
}
else
{
pfactors_rec(num, count+1);
}
}
void pfactors(int num)
{
int count;
for(count = 2; (num > 1); count++)
{
while(num % count == 0)
{
printf("%d\n", count);
num = num / count;
}
}
printf("\n");
}
Implementation in java..
public class PrimeFactor {
public int divisor=2;
void printPrimeFactors(int num)
{
if(num == 1)
return;
if(num%divisor!=0)
{
while(num%divisor!=0)
++divisor;
}
if(num%divisor==0){
System.out.println(divisor);
printPrimeFactors(num/divisor);
}
}
public static void main(String[] args)
{
PrimeFactor obj = new PrimeFactor();
obj.printPrimeFactors(90);
}
}

Resources