I am writing code to find two prime numbers. For this I need to return two values from the function primefactor(). I am using a structure to return the two values.
#include <stdio.h>
#include<stdbool.h>
struct tuple {
long int prime1,prime2;
};
typedef struct tuple primefind;
bool isPrime(int n)
{
// Corner case
if (n <= 1) return false;
// Check from 2 to n-1
for (int i=2; i<n; i )
if (n%i == 0)
return false;
return true;
}
long int nextPrime(long int n)
{
// Base case
if (n <= 1)
return 2;
long int prime = n;
bool found = false;
// Loop continuously until isPrime returns
// true for a number greater than n
while (!found)
{
prime ;
if (isPrime(prime))
found = true;
}
return prime;
}
primefind primeFactor(long int n)
{
primefind tuple1;
long int p, q;
p = 2;
while (p <= (n / p))
{
if (n % p == 0)
{
q = n / (p);
break;
}
p = nextPrime(p);
}
tuple1.prime1 = p;
tuple1.prime2 = q;
return tuple1;
}
int main()
{
return 0;
}
How could I print the value of p,q in the main function which are the two variables of primeFactor function?
Thank you.
CodePudding user response:
Anything wrong with the obvious solution?
primefind primes = primeFactor(n);
printf("%ld %ld\n", primes.prime1, primes.prime2);
You may also consider changing your approach and using function parameters for your return values:
void primeFactor(long int n, long int *prime1, long int *prime2)
{
// ...
*prime1 = 7;
*prime2 = 11;
return;
}
Also please consider only checking factors up to the square root of your number.
CodePudding user response:
Just create an object (struct) in your main()
function and assign it to the return value of primeFactor()
function.
int main()
{
primefind data = primeFactor(50);
printf("prime1 = %ld\n", data.prime1);
printf("prime2 = %ld\n", data.prime2);
return 0;
}
CodePudding user response:
like this
primefind result = primeFactor(42);
printf("%ld %ld \n", result.prime1, result.prime2);