Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calling structure into main function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading