Finding prime factors in C - c

I am trying to generate all the prime factors of a number n. When I give it the number 126 it gives me 2, 3 and 7 but when I give it say 8 it gives me 2, 4 and 8. Any ideas as to what I am doing wrong?
int findPrime(unsigned long n)
{
int testDivisor, i;
i = 0;
testDivisor = 2;
while (testDivisor < n + 1)
{
if ((testDivisor * testDivisor) > n)
{
//If the test divisor squared is greater than the current n, then
//the current n is either 1 or prime. Save it if prime and return
}
if (((n % testDivisor) == 0))
{
prime[i] = testDivisor;
if (DEBUG == 1) printf("prime[%d] = %d\n", i, prime[i]);
i++;
n = n / testDivisor;
}
testDivisor++;
}
return i;
}

You are incrementing testDivisor even when you were able to divide n by it. Only increase it when it is not divisible anymore. This will result in 2,2,2, so you have to modify it a bit further so you do not store duplicates, but since this is a homework assignment I think you should figure that one out yourself :)

Is this based on an algorithm your professor told you to implement or is it your own heuristic? In case it helps, some known algorithms for prime factorization are the Quadratic Sieve and the General Number Field Sieve.

Right now, you aren't checking if any divisors you find are prime. As long as n % testDivisor == 0 you are counting testDivisor as a prime factor. Also, you are only dividing through by testDivisor once. You could fix this a number of ways, one of which would be to replace the statement if (((n % testDivisor) == 0)) with while (((n % testDivisor) == 0)).
Fixing this by adding the while loop also ensures that you won't get composite numbers as divisors, as if they still divide n, a smaller prime factor must have also divided n and the while loop for that prime factor wouldn't have left early.

Here is code to find the Prime Factor:
long GetPrimeFactors(long num, long *arrResult)
{
long count = 0;
long arr[MAX_SIZE];
long i = 0;
long idx = 0;
for(i = 2; i <= num; i++)
{
if(IsPrimeNumber(i) == true)
arr[count++] = i;
}
while(1)
{
if(IsPrimeNumber(num) == true)
{
arrResult[idx++] = num;
break;
}
for(i = count - 1; i >= 0; i--)
{
if( (num % arr[i]) == 0)
{
arrResult[idx++] = arr[i];
num = num / arr[i];
break;
}
}
}
return idx;
}
Reference: http://www.softwareandfinance.com/Turbo_C/Prime_Factor.html

You can use the quadratic sieve algorithm, which factors 170-bit integers in second and 220-bit integers in minute. There is a pure C implementation here that does not require GMP or an external library : https://github.com/michel-leonard/C-Quadratic-Sieve, it's able to provide you a list of the prime factors of N. Thank You.

Related

How to display smallest and biggest divisor?

I have to make a program that displays all the proper divisors of a number(given by the user),basically all except the number itself and 1. If it doesn't have any print that it's prime.All good,done that.
There is one more thing I need to do though in case it does have proper divisors and that is to display the smallest and biggest divisor which I can't figure out how to do ,I tried to do it as if the printed divisors were just one number ignoring the "\n" and using "number % 10" to find the last number and the while loop to find the first number,but that won't work in case let's say the given number is 33 and the biggest divisor is 11.
I'll provide the code for better understanding since my question is kinda fuzzy. Everything is how I want it to be except I don't know how to display the smallest divisor and the biggest divisor.
#include <stdio.h>
int main() {
int n, divisor, smallest, biggest, count = 0;
scanf("%d", &n);
for (divisor = 2; divisor < n; divisor++) {
if (n % divisor == 0) {
printf("%d is divisor of %d\n", divisor, n);
}
}
for (divisor = 1; divisor <= n; divisor++) {
if (n % divisor == 0) {
count++;
}
}
if (count == 2) {
printf("The number does not have proper divisors(it is prime)");
}
return 0;
}
I would modify your code as follows:
#include <stdio.h>
int main()
{
int n,divisor,smallest,biggest,count=0;
scanf("%d",&n);
for(divisor = 2;divisor < n;divisor++)
{
if(n % divisor == 0)
{
count++;
if (count == 1) smallest = divisor;
biggest = divisor;
printf("%d is divisor of %d\n",divisor,n);
}
}
if (count == 0) printf("The number does not have proper divisors(it is prime)");
else printf("%d and %d are the smallest and biggest divisors respectively", smallest, biggest);
return 0;
}
Instead of using two for loops, I merged them into one since they're doing the same thing. Every positive number will be divisible by 1 and itself so it's redundant to use the second for loop. When count is 1, I know that I have found the first divisor so I set smallest equal to that. Also,everytime I find a divisor, I set biggest equal to that so that in the end, biggest is set to the last divisor found (note that you should not use an else clause here, since that will cause the program to not work when the smallest and biggest divisors are equal). I also increment count by 1 everytime a divisor is found in order to check whether the number is prime without modifying your approach too much (there are efficient ways to check for prime numbers, and I encourage you to take a look at them). And finally, I print the smallest and biggest divisors only if they exist, else I print that it is prime.
You can implement minDivisor only, then to find max divisor you can divide value by min divisor:
#include <math.h>
...
/* Returns the smallest non-trivial divisor or 1 if it doesn't exist */
int minDivisor(int value) {
if (value <= 3)
return 1;
/* let's check n for being even */
if (value % 2 == 0)
return 2;
/* We should check up to sqrt(n) only */
int n = (int) (sqrt(value) + 0.5);
for (int divisor = 3; divisor <= n; divisor += 2)
if (value % divisor == 0)
return divisor;
/* prime number */
return 1;
}
Then
int main() {
int n, divisor, smallest, biggest, count = 0;
...
smallest = minDivisor(n);
biggest = n / smallest;
...
Please, fiddle yourself

finding number of numbers which have prime number of factors

The problem is to find the number of divisors of a number
ex-
for 10
ans=4
since 1,2,5,10 are the numbers which are divisors
i.e. they are the factors
constraints are num<=10^6
I have implemented a code for the same but got TLE!!
here is my code
int isprime[MAX];
void seive()
{
int i,
j;
isprime[0] = isprime[1] = 1;
for (i = 4; i < MAX; i += 2)
isprime[i] = 1;
for (i = 3; i * i < MAX; i += 2) {
if (!isprime[i]) {
for (j = i * i; j < MAX; j += 2 * i)
isprime[j] = 1;
}
}
}
int main()
{
seive();
int t;
long long num;
scanf("%d", & t);
while (t--) {
scanf("%lld", & num);
cnt = 0;
for (j = 1; j * j <= num; j++) {
if (num % j == 0) {
cnt++;
if (num / j != j)
cnt++;
}
printf("%lld\n", cnt);
}
return 0;
}
Can somebody help me to optimize it?
I have also searched about it but didnot getting any sucess.
So Please help guys.
You could try computing this mathematically (I'm not sure this will be faster/easier). Basically, given the prime factorization of a number, you should be able to calculate the number of divisors without too much trouble.
If you have an input x decompose into something like
x = p1^a1 * p2^a2 * ... pn^an
Then the number of divisors should be
prod(ai + 1) for i in 1 to n
I would then look at finding the smallest prime < sqrt(x), dividing that out until you're left with just a prime. A sieve might still be useful and I don't know what kind of input you would be getting.
Now consider what the above statement says: the number of divisors in the product of the powers of the prime factorization (plus 1). Thus, if you only every care if the result is prime, then you should only ever consider numbers which are prime, or powers of primes. And within that, you then only need to consider powers such that a1 + 1 is prime.
That should significantly cut down your search space.
If the prime factorization of a number is:
x = p1^e1 * p2^e2 * ... * pk^ek
Then the number of divisors is:
(e1 + 1)*(e2 + 1)* ... *(ek + 1)
For this to be prime, you need all ei to be 0, except one, which needs to be a prime - 1.
This is only true for primes and powers of primes. So you need to find how many powers of primes are in [l, r]. For example, 2^6 has (6 + 1) = 7 prime factors.
Now you just need to sieve enough primes fast enough. You only need to sieve those in [l, r], so an interval of size max 10^6.
To sieve directly in this interval, remove multiples of 2 directly from [l, r], and same for the rest. You can sieve primes up to 10^6 and use those to do the interval sieving later.
You can do the necessary counting while you're sieving as well.

Prime number in C

int prime(unsigned long long n){
unsigned val=1, divisor=7;
if(n==2 || n==3) return 1; //n=2, n=3 (special cases).
if(n<2 || !(n%2 && n%3)) return 0; //if(n<2 || n%2==0 || n%3==0) return 0;
for(; divisor<=n/divisor; val++, divisor=6*val+1) //all primes take the form 6*k(+ or -)1, k[1, n).
if(!(n%divisor && n%(divisor-2))) return 0; //if(n%divisor==0 || n%(divisor-2)==0) return 0;
return 1;
}
The code above is something a friend wrote up for getting a prime number. It seems to be using some sort of sieving, but I'm not sure how it exactly works. The code below is my less awesome version. I would use sqrt for my loop, but I saw him doing something else (probably sieving related) and so I didn't bother.
int prime( unsigned long long n ){
unsigned i=5;
if(n < 4 && n > 0)
return 1;
if(n<=0 || !(n%2 || n%3))
return 0;
for(;i<n; i+=2)
if(!(n%i)) return 0;
return 1;
}
My question is: what exactly is he doing?
Your friend's code is making use of the fact that for N > 3, all prime numbers take the form (6×M±1) for M = 1, 2, ... (so for M = 1, the prime candidates are N = 5 and N = 7, and both those are primes). Also, all prime pairs are like 5 and 7. This only checks 2 out of every 3 odd numbers, whereas your solution checks 3 out of 3 odd numbers.
Your friend's code is using division to achieve something akin to the square root. That is, the condition divisor <= n / divisor is more or less equivalent to, but slower and safer from overflow than, divisor * divisor <= n. It might be better to use unsigned long long max = sqrt(n); outside the loop. This reduces the amount of checking considerably compared with your proposed solution which searches through many more possible values. The square root check relies on the fact that if N is composite, then for a given pair of factors F and G (such that F×G = N), one of them will be less than or equal to the square root of N and the other will be greater than or equal to the square root of N.
As Michael Burr points out, the friend's prime function identifies 25 (5×5) and 35 (5×7) as prime, and generates 177 numbers under 1000 as prime whereas, I believe, there are just 168 primes in that range. Other misidentified composites are 121 (11×11), 143 (13×11), 289 (17×17), 323 (17×19), 841 (29×29), 899 (29×31).
Test code:
#include <stdio.h>
int main(void)
{
unsigned long long c;
if (prime(2ULL))
printf("2\n");
if (prime(3ULL))
printf("3\n");
for (c = 5; c < 1000; c += 2)
if (prime(c))
printf("%llu\n", c);
return 0;
}
Fixed code.
The trouble with the original code is that it stops checking too soon because divisor is set to the larger, rather than the smaller, of the two numbers to be checked.
static int prime(unsigned long long n)
{
unsigned long long val = 1;
unsigned long long divisor = 5;
if (n == 2 || n == 3)
return 1;
if (n < 2 || n%2 == 0 || n%3 == 0)
return 0;
for ( ; divisor<=n/divisor; val++, divisor=6*val-1)
{
if (n%divisor == 0 || n%(divisor+2) == 0)
return 0;
}
return 1;
}
Note that the revision is simpler to understand because it doesn't need to explain the shorthand negated conditions in tail comments. Note also the +2 instead of -2 in the body of the loop.
He's checking for the basis 6k+1/6k-1 as all primes can be expressed in that form (and all integers can be expressed in the form of 6k+n where -1 <= n <= 4). So yes it is a form of sieving.. but not in the strict sense.
For more:
http://en.wikipedia.org/wiki/Primality_test
In case the 6k+-1 portion is confusing, note that you can perform some factorization of most forms of 6k+n and some are obviously composite and some need to be tested.
Consider numbers:
6k + 0 -> composite
6k + 1 -> not obviously composite
6k + 2 -> 2(3k+1) --> composite
6k + 3 -> 3(2k+1) --> composite
6k + 4 -> 2(3k+2) --> composite
6k + 5 -> not obviously composite
I've not seen this little trick before, so it's neat, but of limited utility since a sieve of Eratosthenese is more efficient for finding many small prime numbers, and larger prime numbers benefit from faster, more intelligent, tests.
#include<stdio.h>
int main()
{
int i,j;
printf("enter the value :");
scanf("%d",&i);
for (j=2;j<i;j++)
{
if (i%2==0 || i%j==0)
{
printf("%d is not a prime number",i);
return 0;
}
else
{
if (j==i-1)
{
printf("%d is a prime number",i);
}
else
{
continue;
}
}
}
}
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}

Find the largest prime number factor?

I need to find
The prime factors of 13195 are 5, 7, 13 and 29.
/ * Largest is 377. * /
What is the largest prime factor of the number 600851475143 ?
#include<stdio.h>
int main()
{
int i, j = 0;
/*Code works really fine for 13195 or 26*/
long value, large = 600851475143 /*13195*/;
for(value = (large - 1) ; value >= 3; value--)
{
if(large % value == 0)
{
/*printf("I am here \n");*/
if((value % 2 != 0) && (value % 3 != 0) && (value % 5 != 0) && (value % 7 != 0) )
{
j = 1;
break;
}
}
}
if (j == 1)
{
printf("%ld", value);
}
return 0;
}
Where it is going wrong?
600851475143 is too big to fit in 32 bit integer. long may be 32 bit on your machine. You need to use 64 bit type. The exact data type will be dependent on your platform, compiler.
Your prime checking code is wrong. You are assuming that if something is not devided by 2, 3, 5, 7 then that is prime.
The most important thing that is wrong here is that your code is too slow: even if you fix other issues, such as using a wrong data type for your integers and trying out some divisors that are definitely not prime, iterating by one down from 10^11 will simply not finish in your computer's lifetime is extremely wasteful.
I highly recommend that you read through the example on page 35 of this classic book, where Dijkstra takes you through the process of writing a program printing the first 1000 prime numbers. This example should provide enough mathematical intuition to you to speed up your own calculations, including the part where you start your search from the square root of the number that you are trying to factor.
600851475143 is probably above the precision of your platform's long data type. It requires at least 40 bits to store. You can use this to figure out how many bits you have:
#include <limits.h>
printf("my compiler uses %u bits for the long data type\n", (unsigned int) (CHAR_BIT * sizeof (long)));
#include<stdio.h>
//Euler problem #3
int main(){
long long i, sqi;
long long value, large = 600851475143LL;
long long max = 0LL;
i = 2LL;
sqi = 4LL; //i*i
for(value = large; sqi <= value ; sqi += 2LL * i++ + 1LL){
while(value % i == 0LL){
value /= (max=i);
}
}
if(value != 1LL && value != large){
max = value;
}
if(max == 0LL){
max = large;
}
printf("%lld\n", max);
return 0;
}
You need to add an L as suffix to a number that overflow MAX INT, so this line:
long value, large = 600851475143;
Should be:
long value, large = 600851475143L;
// ^
In order to do this you need to establish that the value is prime - i.e. that is has no prime factors.
Now your little piece of code checking 3/5/7 simply isn't good enough - you need to check is value has ANY lower prime factors (for example 11/13/17).
From a strategic perspective if you want to use this analysis you need to check a list of every prime factor you have found so far and check against them as you are checking against the first 3 primes.
An easier (but less efficient) method would be to write an IsPrimeFunction() and check the primality of the each divisor and store the largest.
public class LargeFactor{
public static void main(String []args){
long num = 600851475143L;
long largestFact = 0;
long[] factors = new long[2];
for (long i = 2; i * i < num; i++) {
if (num % i == 0) { // It is a divisor
factors[0] = i;
factors[1] = num / i;
for (int k = 0; k < 2; k++) {
boolean isPrime = true;
for (long j = 2; j * j < factors[k]; j++) {
if (factors[k] % j == 0) {
isPrime = false;
break;
}
}
if (isPrime && factors[k] > largestFact) {
largestFact = factors[k];
}
}
}
}
System.out.println(largestFact);
}
}
Above code utilises the fact that we only need to check all numbers up to the square root when looking for factors.

Finding largest prime factor of a composite number in c

I am accepting a composite number as an input. I want to print all its factors and also the largest prime factor of that number. I have written the following code. It is working perfectly ok till the number 51. But if any number greater than 51 is inputted, wrong output is shown. how can I correct my code?
#include<stdio.h>
void main()
{
int i, j, b=2, c;
printf("\nEnter a composite number: ");
scanf("%d", &c);
printf("Factors: ");
for(i=1; i<=c/2; i++)
{
if(c%i==0)
{
printf("%d ", i);
for(j=1; j<=i; j++)
{
if(i%j > 0)
{
b = i;
}
if(b%3==0)
b = 3;
else if(b%2==0)
b = 2;
else if(b%5==0)
b = 5;
}
}
}
printf("%d\nLargest prime factor: %d\n", c, b);
}
This is a bit of a spoiler, so if you want to solve this yourself, don't read this yet :). I'll try to provide hints in order of succession, so you can read each hint in order, and if you need more hints, move to the next hint, etc.
Hint #1:
If divisor is a divisor of n, then n / divisor is also a divisor of n. For example, 100 / 2 = 50 with remainder 0, so 2 is a divisor of 100. But this also means that 50 is a divisor of 100.
Hint #2
Given Hint #1, what this means is that we can loop from i = 2 to i*i <= n when checking for prime factors. For example, if we are checking the number 100, then we only have to loop to 10 (10*10 is <= 100) because by using hint #1, we will get all the factors. That is:
100 / 2 = 50, so 2 and 50 are factors
100 / 5 = 20, so 5 and 20 are factors
100 / 10 = 10, so 10 is a factor
Hint #3
Since we only care about prime factors for n, it's sufficient to just find the first factor of n, call it divisor, and then we can recursively find the other factors for n / divisor. We can use a sieve approach and mark off the factors as we find them.
Hint #4
Sample solution in C:
bool factors[100000];
void getprimefactors(int n) {
// 0 and 1 are not prime
if (n == 0 || n == 1) return;
// find smallest number >= 2 that is a divisor of n (it will be a prime number)
int divisor = 0;
for(int i = 2; i*i <= n; ++i) {
if (n % i == 0) {
divisor = i;
break;
}
}
if (divisor == 0) {
// we didn't find a divisor, so n is prime
factors[n] = true;
return;
}
// we found a divisor
factors[divisor] = true;
getprimefactors(n / divisor);
}
int main() {
memset(factors,false,sizeof factors);
int f = 1234;
getprimefactors(f);
int largest;
printf("prime factors for %d:\n",f);
for(int i = 2; i <= f/2; ++i) {
if (factors[i]) {
printf("%d\n",i);
largest = i;
}
}
printf("largest prime factor is %d\n",largest);
return 0;
}
Output:
---------- Capture Output ----------
> "c:\windows\system32\cmd.exe" /c c:\temp\temp.exe
prime factors for 1234:
2
617
largest prime factor is 617
> Terminated with exit code 0.
I presume you're doing this to learn, so I hope you don't mind a hint.
I'd start by stepping through your algorithm on a number that fails. Does this show you where the error is?
You need to recode so that your code finds all the prime numbers of a given number, instead of just calculating for the prime numbers 2,3, and 5. In other words, your code can only work with the number you are calculating is a prime number or is a multiple of 2, 3, or 5. But 7, 11, 13, 17, 19 are also prime numbers--so your code should simply work by finding all factors of a particular number and return the largest factor that is not further divisible.
Really, this is very slow for all but the smallest numbers (below, say, 100,000). Try finding just the prime factors of the number:
#include <cmath>
void addfactor(int n) {
printf ("%d\n", n);
}
int main()
{
int d;
int s;
int c = 1234567;
while (!(c&1)) {
addfactor(2);
c >>= 1;
}
while (c%3 == 0) {
addfactor(3);
c /= 3;
}
s = (int)sqrt(c + 0.5);
for (d = 5; d <= s;) {
while (c % d == 0) {
addfactor(d);
c /= d;
s = (int)sqrt(c + 0.5);
}
d += 2;
while (c % d == 0) {
addfactor(d);
c /= d;
s = (int)sqrt(c + 0.5);
}
d += 4;
}
if (c > 1)
addfactor(c);
return 0;
}
where addfactor is some kind of macro that adds the factor to a list of prime factors. Once you have these, you can construct a list of all the factors of the number.
This is dramatically faster than the other code snippets posted here. For a random input like 10597959011, my code would take something like 2000 bit operations plus 1000 more to re-constitute the divisors, while the others would take billions of operations. It's the difference between 'instant' and a minute in that case.
Simplification to dcp's answer(in an iterative way):
#include <stdio.h>
void factorize_and_print(unsigned long number) {
unsigned long factor;
for(factor = 2; number > 1; factor++) {
while(number % factor == 0) {
number = number / factor;
printf("%lu\n",factor);
}
}
}
/* example main */
int main(int argc,char** argv) {
if(argc >= 2) {
long number = atol(argv[1]);
factorize_and_print(number);
} else {
printf("Usage: %s <number>%<number> is unsigned long", argv[0]);
}
}
Note: There is a number parsing bug here that is not getting the number in argv correctly.

Resources