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);
}
}
Related
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.");
}
}
The below program correctly outputs the divisors of the input numbers, but it does not correctly report whether the inputs are prime. For example, when the input is 13, it does not print "The number you entered is a prime number." What's wrong with it?
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
the reason is that scanf is in a while loop if there's a valid input but you are checking & printing if it's prime outside of the loop... if you expect this program just get one input and validate it once, then you just need to change that while to if:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.");
}
return 0;
}
If you expect this program goes in a loop to keep on getting input and validating if it's prime or not, this should do the job:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (1)
{
isPrime=true;
printf("Enter a number: ");
if (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
}
return 0;
}
You have missed 2 things !
You should have printed inside the while loop !
In addition to that you didn't change the status of isPrime=true; !
Hope this answers your question !
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num;
bool isPrime = true;
while (scanf("%d", &num) == 1)
{
for (int i = 2; i * i <= num; ++i)
{
if (num % i == 0)
{
if (i * i != num)
{
printf("%d ve %d, divides %d\n", i, num / i, num);
}
else
{
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (isPrime)
{
printf("The number you entered is a prime number.\n");
}
isPrime=true;
}
return 0;
}
When you entered a prime number, your while loop doesn't break. Try it:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int num;
bool isPrime = true, finishIt = false;
printf("Enter a number: ");
while (1) {
while (1) {
if (scanf("%d", &num) != 1)
continue;
if (num == 0) {
finishIt = true;
break;
}
int i;
for (i = 2; i * i <= num; ++i) {
if (num % i == 0) {
if (i * i != num) {
printf("%d ve %d, divides %d\n", i, num / i, num);
} else {
printf("%d divides %d.\n", i, num);
}
isPrime = false;
}
}
if (i * i >= num)
break;
}
if (isPrime) {
printf("The number you entered is a prime number.");
}
isPrime = true;
if (finishIt)
break;
}
return 0;
}
I am learning about functions and how to call upon them and use them in class. I don't quite understand where I've gone wrong here. I know that there are some mistakes around the int main part. I have asked my teacher and he is reluctant on giving me an example that would solve my problems or help me out. I think my main problem is at factorial_result = factorial();
#include <stdio.h>
void mystamp(void)
{
printf("My name is John Appleseed\n");
printf("My lab time is 12:30 on Sunday\n");
return;
}
int getnum(void)
{
int local_var;
printf("Please enter an integer: ");
scanf("%d%*c", local_var);
return(local_var);
}
int factorial(void)
{
int x,f=1,local_var;
for(x=1; x <= local_var; x++)
f = f * x;
return(f);
}
int main(void)
{
int result;
int factorial_result;
mystamp();
result = getnum();
factorial_result = factorial();
printf("You typed %d\n", result);
printf("The factorial is %d\n", factorial_result);
return;
}
Declare local_var as a global variable and do:
local_var = getnum();
OR
Change main() to:
int main(void)
{
int result;
int factorial_result;
mystamp();
result = getnum();
factorial_result = factorial(result);
printf("You typed %d\n", result);
printf("The factorial is %d\n", factorial_result);
return;
}
And factorial() to:
int factorial(int n)
{
int x,f=1,local_var=n;
for(x=1; x <= local_var; x++)
f = f * x;
return(f);
}
Your factorial should be calculated based on the input( i.e in your case int result ).
So, your method factorial() should looks as follows :
int factorial( int number )
{
int factorial_value = 1;
while( number > 0 )
{
factorial_value *= number;
number--;
}
return factorial_value;
}
Then, the correct factorial would be returned and printed accordingly ! Regarding the scope of the variables that you have used, see the comments under your question.
#include <stdio.h>
int factorial(int);
int main()
{
int num;
int result;
printf("Enter a number to find it's Factorial: ");
scanf("%d", &num);
if (num < 0)
{
printf("Factorial of negative number not possible\n");
}
else
{
result = factorial(num);
printf("The Factorial of %d is %d.\n", num, result);
}
return 0;
}
int factorial(int num)
{
if (num == 0 || num == 1)
{
return 1;
}
else
{
return(num * factorial(num - 1));
}
}
This is a simple factorial program using recursion calling function !
include
int main()
{
int c, n, fact = 1;
printf("Enter a number to calculate its factorial\n"); scanf("%d", &n);
for (c = 1; c <= n; c++) fact = fact * c;
printf("Factorial of %d = %d\n", n, fact);
return 0;
}
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 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;
}