Finding prime factors - c++

#include <iostream>
using namespace std;
void whosprime(long long x)
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{
for(int z = 2; z <= x; z++)
{
if((i != z) && (i%z == 0))
{
imPrime = false;
break;
}
}
if(imPrime && x%i == 0)
cout << i << endl;
imPrime = true;
}
}
int main()
{
long long r = 600851475143LL;
whosprime(r);
}
I'm trying to find the prime factors of the number 600851475143 specified by Problem 3 on Project Euler (it asks for the highest prime factor, but I want to find all of them). However, when I try to run this program I don't get any results. Does it have to do with how long my program is taking for such a large number, or even with the number itself?
Also, what are some more efficient methods to solve this problem, and do you have any tips as to how can I steer towards these more elegant solutions as I'm working a problem out?
As always, thank you!

Your algorithm is wrong; you don't need i. Here's pseudocode for integer factorization by trial division:
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
I'll leave it to you to translate to C++ with the appropriate integer datatypes.
Edit: Fixed comparison (thanks, Harold) and added discussion for Bob John:
The easiest way to understand this is by an example. Consider the factorization of n = 13195. Initially z = 2, but dividing 13195 by 2 leaves a remainder of 1, so the else clause sets z = 3 and we loop. Now n is not divisible by 3, or by 4, but when z = 5 the remainder when dividing 13195 by 5 is zero, so output 5 and divide 13195 by 5 so n = 2639 and z = 5 is unchanged. Now the new n = 2639 is not divisible by 5 or 6, but is divisible by 7, so output 7 and set n = 2639 / 7 = 377. Now we continue with z = 7, and that leaves a remainder, as does division by 8, and 9, and 10, and 11, and 12, but 377 / 13 = 29 with no remainder, so output 13 and set n = 29. At this point z = 13, and z * z = 169, which is larger than 29, so 29 is prime and is the final factor of 13195, so output 29. The complete factorization is 5 * 7 * 13 * 29 = 13195.
There are better algorithms for factoring integers using trial division, and even more powerful algorithms for factoring integers that use techniques other than trial division, but the algorithm shown above will get you started, and is sufficient for Project Euler #3. When you're ready for more, look here.

A C++ implementation using #user448810's pseudocode:
#include <iostream>
using namespace std;
void factors(long long n) {
long long z = 2;
while (z * z <= n) {
if (n % z == 0) {
cout << z << endl;
n /= z;
} else {
z++;
}
}
if (n > 1) {
cout << n << endl;
}
}
int main(int argc, char *argv[]) {
long long r = atoll(argv[1]);
factors(r);
}
// g++ factors.cpp -o factors ; factors 600851475143
Perl implementation with the same algorithm is below.
Runs ~10-15x slower (Perl 0.01 seconds for n=600851475143)
#!/usr/bin/perl
use warnings;
use strict;
sub factors {
my $n = shift;
my $z = 2;
while ($z * $z <= $n) {
if ( $n % $z ) {
$z++;
} else {
print "$z\n";
$n /= $z;
}
}
if ( $n > 1 ) {
print "$n\n"
}
}
factors(shift);
# factors 600851475143

600851475143 is outside of the range of an int
void whosprime(int x) //<-----fix heere ok?
{
bool imPrime = true;
for(int i = 1; i <= x; i++)
{...
...

Try below code:
counter = sqrt(n)
i = 2;
while (i <= counter)
if (n % i == 0)
output i
else
i++

Edit: I'm wrong (see comments). I would have deleted, but the way in which I'm wrong has helped indicate what specifically in the program takes so long to produce output, so I'll leave it :-)
This program should immediately print 1 (I'm not going to enter a debate whether that's prime or not, it's just what your program does). So if you're seeing nothing then the problem isn't execution speed, there muse be some issue with the way you're running the program.

Here is my code that worked pretty well to find the largest prime factor of any number:
#include <iostream>
using namespace std;
// --> is_prime <--
// Determines if the integer accepted is prime or not
bool is_prime(int n){
int i,count=0;
if(n==1 || n==2)
return true;
if(n%2==0)
return false;
for(i=1;i<=n;i++){
if(n%i==0)
count++;
}
if(count==2)
return true;
else
return false;
}
// --> nextPrime <--
// Finds and returns the next prime number
int nextPrime(int prime){
bool a = false;
while (a == false){
prime++;
if (is_prime(prime))
a = true;
}
return prime;
}
// ----- M A I N ------
int main(){
int value = 13195;
int prime = 2;
bool done = false;
while (done == false){
if (value%prime == 0){
value = value/prime;
if (is_prime(value)){
done = true;
}
} else {
prime = nextPrime(prime);
}
}
cout << "Largest prime factor: " << value << endl;
}
Keep in mind that if you want to find the largest prime factor of extremely large number, you have to use 'long' variable type instead of 'int' and tweak the algorithm to process faster.

short and clear vesion:
int main()
{
int MAX = 13195;
for (int i = 2; i <= MAX; i++)
{
while (MAX % i == 0)
{
MAX /= i;
cout << i << ", " << flush; // display only prime factors
}
return 0;
}

This is one of the easiest and simple-to-understand solutions of your question.
It might not be efficient like other solutions provided above but yes for those who are the beginner like me.
int main() {
int num = 0;
cout <<"Enter number\n";
cin >> num;
int fac = 2;
while (num > 1) {
if (num % fac == 0) {
cout << fac<<endl;
num=num / fac;
}
else fac++;
}
return 0;
}

# include <stdio.h>
# include <math.h>
void primeFactors(int n)
{
while (n%2 == 0)
{
printf("%d ", 2);
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i+2)
{
while (n%i == 0)
{
printf("%d ", i);
n = n/i;
}
}
if (n > 2)
printf ("%d ", n);
}
int main()
{
int n = 315;
primeFactors(n);
return 0;
}

Simple way :
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
ll largeFactor(ll n)
{
ll ma=0;
for(ll i=2; i*i<=n; i++)
{
while(n%i == 0)
{
n=n/i;
ma=i;
}
}
ma = max(ma, n);
return ma;
}
int main()
{
ll n;
cin>>n;
cout<<largeFactor(n)<<endl;
return 0;
}
Implementation using prime sieve ideone.

Since 600851475143 is out of scope for int as well as single long type wont work here hence here to solve we have to define our own type here with the help of typedef.
Now the range of ll is some what around 9,223,372,036,854,775,807.
typedef long long int LL

Try this code. Absolutely it's the best and the most efficient:
long long number;
bool isRepetitive;
for (int i = 2; i <= number; i++) {
isRepetitive = false;
while (number % i == 0) {
if(!isRepetitive){
cout << i << endl;
isRepetitive = true;
}
number /= i;
}
}
Enjoy! ☻

Related

How do I prime factorize large numbers?

I'm trying to solve Project Euler third question but while my code works perfectly with small numbers when I try to use big number it doesn't give me any answer.
#include<iostream>
using std :: cout;
using std :: cin;
using std :: endl;
int main()
{
long long int a = 0, bigPrime = 0, smallPrime = 2, prime = 0;
cout << "Please enter a number...!" << endl;
cin >> a;
for(long long int i = 2 ; i < a ; i++)
{
for(long long int c = 2 ; c < i ; c++)
{
if(i % c != 0)
{
prime = i;
}
else
{
prime = 0;
break;
}
}
if(prime > 0 )
{
if(a % prime == 0)
{
bigPrime = prime;
}
}
}
cout << "The biggest prime is = " << bigPrime << endl;
return 0;
}
That's my bad code :)
i am using ubuntu linux and g++
what is wrong with my code and how can i improve it?
You can improve your program using one simple trick:
Every time you find a divisor d, divide your number by d.
That means that for every divisor found, your number gets smaller, making the remaining part easier to factor.
As a bonus, that means you don't need to be so careful about only using primes as divisors. Every time a divisor is found, it's the smallest divisor of the current number, and since it's the smallest divisor, it must be a prime. That saves a whole level of looping.
The factors are extracted in order from smallest to highest, so in the end what you have is the highest prime factor - the answer to this challenge.
This is not a fast algorithm, but 600851475143 is not a large number and this algorithm will factor it no problem.
For examle (on ideone):
for (long long int d = 2; d * d <= a; d++) {
if (a % d == 0) {
a /= d;
d--; // this is to handle repeated factors
}
}
I also used the old d * d <= a trick but you don't even need it here. It helps if the highest factor is high, and in this example it is not.
But the problem states that you just need to find the biggest prime of 600851475143, right? Why don't you just iterate from sqrt(600851475143) to 2 and return the first number that is a prime?
bool isPrime(uint64_t num)
{
bool result = true;
for(uint64_t i = 2; i < std::sqrt(num); ++i)
{
if(num % i == 0)
{
result = false;
break;
}
}
return result;
}
int main()
{
uint64_t num = 600851475143;
uint64_t i = std::sqrt(num);
while (i > 1)
{
i--;
if (num%i != 0) continue;
if (isPrime(i))
{
break;
}
}
std::cout << i << std::endl;
return 0;
}
For sure it can be done faster, but it takes 10ms on my machine, so I guess it's not terrible.
#include <iostream>
using namespace std;
typedef long long ulong;
int main()
{
ulong num = 600851475143;
ulong div = num;
ulong p = 0;
ulong i = 2;
while (i * i <= div)
{
if (div % i == 0)
{
div /= i;
p = i;
}
else {
i++;
}
}
if (div > p)
{
p = div;
}
cout << p << endl;
return 0;
}

Console Application is not running and shows nothing

The problem is to solve this.
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
I wrote this code
#include <iostream>
#include <math.h>
using namespace std;
bool prime(long int a);
int main()
{
long int b = 600851475143/2;
long int k;
for(long int i = 1; i <= b ; i++)
{
if(b % i == 0 && prime(i) == true)
{
k = i;
}
}
cout << k << endl;
return 0;
}
bool prime(long int a)
{
bool p = true;
for(long int i = 2; i <= sqrt(a) && p == true ; i++)
if(a % i == 0) p = false;
return p;
}
and when I execute after a build, it opens a console , and shows nothing
Add a cout statement inside the for loop in main. Your program is running, it's just taking a long time.
The code is fine. 600851475143/2 is just a large number, so you have to wait some minutes till the result will be printed.
Further you're testing kind of twice if it a prime which makes the complexity unnecessarily much higher.
Try this:
long int b = 600851475143/2;
long int k = b;
for(long int i = 2; i < b ; i++)
{
if(b % i == 0)
{
k = i;
break;
}
}
cout << k << endl;

How to check if a number is prime in a more efficient manner?

So I have the following problem. They give me an array w/ n numbers and I have to print if it contains any prime numbers using "Divide et Impera". I solved the problem but it gets only 70/100 because it isn't efficient(they say).
#include <iostream>
using namespace std;
bool isPrime(int x){
if(x == 2) return false;
for(int i = 2; i <= x/2; ++i)
if(x%i==0) return false;
return true;
}
int existaP(int a[], int li, int ls){
if(li==ls)
if(isPrime(a[li]) == true) return 1;
else return 0;
else return existaP(a, li, (li+ls)/2)+existaP(a, (li+ls)/2+1, ls);
}
int main(){
int n, a[10001];
cin >> n;
for(int i = 1; i<=n; ++i) cin >> a[i];
if(existaP(a,1,n) >= 1) cout << "Y";
else cout << "N";
return 0;
}
The lowest hanging fruit here is your stopping conditional
i <= x/2
which can be replaced with
i * i <= x
having taken care to ensure you don't overflow an int.This is because you only need to go up to the square root of x, rather than half way. Perhaps i <= x / i is better still as that avoids the overflow; albeit at the expense of a division which can be relatively costly on some platforms.
Your algorithm is also defective for x == 2 as you have the incorrect return value. It would be better if you dropped that extra test, as the ensuing loop covers it.
Here is an efficinent way to check prime number.
bool isPrime(int num) {
if(num <= 1) return false;
if (num <= 3) return true;
int range = sqrt(num);
// This is checked so that we can skip
// middle five numbers in below loop
if (num % 2 == 0 || num % 3 == 0)
return false;
for (int i = 5; i <= range; i += 6)
if (num % i == 0 || num % (i + 2) == 0)
return false;
return true;
}
A stander way(maybe..?) is just check from i = 0 to the sqrt(number)
bool isPrime(int num){
if(num == 1) return false;
for(int i = 2;i<=sqrt(num);i++){
if(num % i == 0) return false;
}
return true;
}
bool isprime(int x)
{
if(x <= 1) return false;
if(x == 2 || x == 3) return true;
if(x % 2 == 0 || x % 3 == 0) return false;
if((x - 1) % 6 != 0 && (x + 1) % 6 != 0) return false;
for(int i = 5; i * i <= x; i += 6)
{
if(x % i == 0 || x % (i + 2) == 0) return false;
}
return true;
}
If prime numbers need to be printed for a particular range or to determine whether a number is prime or not, the sieve of the eratosthenes algorithm is probably preferable as it is very efficient in terms of time complexity O( n * log2( log2(n) ) ), but the space complexity of this algorithm can cause an issue if the numbers are exceeding certain memory limit.
We can optimize this simpler algorithm which has a time complexity of O(n1/2) by introducing few additional checks based on this thoerem as shown in the above isprime code block.
Despite the fact that Sieve of Erathosthenes algorithm is efficient in terms of time complexity under space restrictions, the above provided isprime code block can be utilized, and there are numerous variations of the Sieve of Erathosthenes algorithm that perform considerably better, as explained in this link.
Many more algorithms exist, but in terms of solving coding challenges, this one is simpler and more convenient. You can learn more about them by clicking on the following links:
https://www.quora.com/Whats-the-best-algorithm-to-check-if-a-number-is-prime
https://www.baeldung.com/cs/prime-number-algorithms#:~:text=Most%20algorithms%20for%20finding%20prime,test%20or%20Miller%2DRabin%20method.
Your code will give a wrong answer if n is 1.
Your time complexity can be decreased to sqrt(n) , where n is the number.
Here is the code
bool isPrime(long int n)
{
if (n == 1)
{
return false;
}
int i = 2;
while (i*i <= n)
{
if (n % i == 0)
{
return false;
}
i += 1;
}
return true;
}
The "long int" will help to avoid overflow.
Hope this helps. :-)
If the numbers are not too big you could also try to solve this using the sieve of Eratosthenes:
#include <iostream>
#include <array>
using namespace std;
constexpr int LIMIT = 100001;
// not_prime because global variables are initialized with 0
bool not_prime[LIMIT];
void sieve() {
int i, j;
not_prime[2] = false;
for(int i = 2; i < LIMIT; ++i)
if(!not_prime[i])
for(int j = i + i; j < LIMIT; j += i)
not_prime[j] = true;
}
int existaP(int a[], int li, int ls){
if(li==ls)
if(!not_prime[a[li]] == true)
return 1;
else
return 0;
else
return existaP(a, li, (li + ls) / 2) + existaP(a, (li + ls) / 2 + 1, ls);
}
int main(){
int n, a[10001];
cin >> n;
for(int i = 1; i<=n; ++i) cin >> a[i];
sieve();
if(existaP(a,1,n) >= 1) cout << "Y";
else cout << "N";
return 0;
}
Basically when you encounter a prime all the numbers that are a multiple of it won't be primes.
P.S.: Acum am vazut ca esti roman :)
Poti sa te uiti aici pentru a optimiza si mai mult algoritmul: https://infoarena.ro/ciurul-lui-eratostene
Another inefficiency not yet mentioned is existaP(a, li, (li+ls)/2) + existaP(a, (li+ls)/2+1, ls);
In particular, the problem here is the +. If you know existaP(a, li, (li+ls)/2) > 0, then existaP(a, (li+ls)/2+1, ls) no longer matters. In other words, you're currently counting the exact number of unique factors, but as soon as you know a number has at least two factors you know it's not prime.
Here is one efficient way to check a given number is prime.
bool isprime(int n) {
if(n<=1)
return false;
if(n<=3)
return true;
if(n%2==0||n%3==0)
return false;
for(int i=5;i*i<=n;i=i+6) {
if(n%i==0||n%(i+2)==0)
return false;
}
return true;
}
This is a much faster algorithm in my opinion. It works on the Euclidean algorithm to calculate H.C.F. Basically, I check if the HCF of the number AND the consecutively second number is 1; and if the number itself is divisible by either 2 or 3. Don't ask how I mathematically reached the solution, it just struck me :D. The time complexity of this solution is O(log (max(a,b))), which is notably smaller than the time complexity of the program which runs a loop counter 2 to sqrt(n) is O(sqrt(n)).
#include <iostream>
using namespace std;
int hcf(int, int);
int hcf(int a, int b)
{
if (b == 0)
{
return a;
}
return hcf(b, a % b);
}
int main()
{
int a;
cout << "\nEnter a natural number: ";
cin >> a;
if(a<=0)
{
cout << "\nFor conventional reasons we keep the discussion of primes to natural numbers in this program:) (Read: Ring of Integers / Euclid's Lemma)";
return 0;
}
if (a == 1)
{
cout << "\nThe number is neither composite nor prime :D";
return 0;
}
if (a == 2)
{
cout << "\nThe number is the only even Prime :D";
return 0;
}
if (hcf(a, a + 2) == 1)
{
if (a % 2 != 0 && a % 3 != 0)
{
cout << "\nThe number is a Prime :D";
return 0;
}
}
cout << "\nThe number is not a Prime D:";
return 0;
}
Correct me if I'm wrong. I'm a student.

How do I find the smallest number than can be divided by all numbers 1:n with no remainder?

I have been trying to solve problem number 5 on Project Euler which goes like
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
I decided to go a step further and I decided I'd make it find the smallest positive number that is evenly divisible by all of the numbers from 1 to limit where limit is user-defined.
Problem starts when I execute my program, it immediately prints out 0. I tried tracing my code but that didn't work out.
#include <iostream>
using std::cout;
using std::cin;
bool isRemainderFree(int num, int limit){
bool bIsRemainderFree = true;
if(num < limit){
bIsRemainderFree = false;
}else{
for(int i=1; i <= limit; i++){
if(num % i != 0){
bIsRemainderFree = false;
break;
}
}
}
return bIsRemainderFree;
}
int smallestMultiple(int limit){
int smallestNum = 10;
for(int i=1; i <= limit; i++){
bool bFree = isRemainderFree(i, 10);
if(bFree){
cout << i << " is divisible by all numbers from 1 to " << limit << ".\n";
smallestNum = i;
return smallestNum;
break;
}
}
}
int main(){
int limit;
cin >> limit;
int smallestNum = smallestMultiple(limit);
cout << smallestNum;
return 0;
}
The answer should be simply the LCM of all numbers, it can be easily done in the following way
int gcd(int a, int b){
if(b==0)
return a;
return gcd(b, a%b);
}
int main() {
int limit = 10, lcm = 1;
for(int i=1; i<=limit; i++){
lcm = (lcm * i)/gcd(lcm,i);
}
printf("%d\n", lcm); // prints 2520
return 0;
}
PYTHON CODE
import math
# Returns the lcm of first n numbers
def lcm(n):
ans = 1
for i in range(1, n + 1):
ans = int((ans * i)/math.gcd(ans, i))
return ans
# main
n = 20
print (lcm(n))

Efficiently getting all divisors of a given number

According to this post, we can get all divisors of a number through the following codes.
for (int i = 1; i <= num; ++i){
if (num % i == 0)
cout << i << endl;
}
For example, the divisors of number 24 are 1 2 3 4 6 8 12 24.
After searching some related posts, I did not find any good solutions. Is there any efficient way to accomplish this?
My solution:
Find all prime factors of the given number through this solution.
Get all possible combinations of those prime factors.
However, it doesn't seem to be a good one.
Factors are paired. 1 and 24, 2 and 12, 3 and 8, 4 and 6.
An improvement of your algorithm could be to iterate to the square root of num instead of all the way to num, and then calculate the paired factors using num / i.
You should really check till square root of num as sqrt(num) * sqrt(num) = num:
Something on these lines:
int square_root = (int) sqrt(num) + 1;
for (int i = 1; i < square_root; i++) {
if (num % i == 0&&i*i!=num)
cout << i << num/i << endl;
if (num % i == 0&&i*i==num)
cout << i << '\n';
}
There is no efficient way in the sense of algorithmic complexity (an algorithm with polynomial complexity) known in science by now. So iterating until the square root as already suggested is mostly as good as you can be.
Mainly because of this, a large part of the currently used cryptography is based on the assumption that it is very time consuming to compute a prime factorization of any given integer.
Here's my code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
#define pii pair<int, int>
#define MAX 46656
#define LMT 216
#define LEN 4830
#define RNG 100032
unsigned base[MAX / 64], segment[RNG / 64], primes[LEN];
#define sq(x) ((x)*(x))
#define mset(x,v) memset(x,v,sizeof(x))
#define chkC(x,n) (x[n>>6]&(1<<((n>>1)&31)))
#define setC(x,n) (x[n>>6]|=(1<<((n>>1)&31)))
// http://zobayer.blogspot.com/2009/09/segmented-sieve.html
void sieve()
{
unsigned i, j, k;
for (i = 3; i<LMT; i += 2)
if (!chkC(base, i))
for (j = i*i, k = i << 1; j<MAX; j += k)
setC(base, j);
primes[0] = 2;
for (i = 3, j = 1; i<MAX; i += 2)
if (!chkC(base, i))
primes[j++] = i;
}
//http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/
vector <pii> factors;
void primeFactors(int num)
{
int expo = 0;
for (int i = 0; primes[i] <= sqrt(num); i++)
{
expo = 0;
int prime = primes[i];
while (num % prime == 0){
expo++;
num = num / prime;
}
if (expo>0)
factors.push_back(make_pair(prime, expo));
}
if ( num >= 2)
factors.push_back(make_pair(num, 1));
}
vector <int> divisors;
void setDivisors(int n, int i) {
int j, x, k;
for (j = i; j<factors.size(); j++) {
x = factors[j].first * n;
for (k = 0; k<factors[j].second; k++) {
divisors.push_back(x);
setDivisors(x, j + 1);
x *= factors[j].first;
}
}
}
int main() {
sieve();
int n, x, i;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> x;
primeFactors(x);
setDivisors(1, 0);
divisors.push_back(1);
sort(divisors.begin(), divisors.end());
cout << divisors.size() << "\n";
for (int j = 0; j < divisors.size(); j++) {
cout << divisors[j] << " ";
}
cout << "\n";
divisors.clear();
factors.clear();
}
}
The first part, sieve() is used to find the prime numbers and put them in primes[] array. Follow the link to find more about that code (bitwise sieve).
The second part primeFactors(x) takes an integer (x) as input and finds out its prime factors and corresponding exponent, and puts them in vector factors[]. For example, primeFactors(12) will populate factors[] in this way:
factors[0].first=2, factors[0].second=2
factors[1].first=3, factors[1].second=1
as 12 = 2^2 * 3^1
The third part setDivisors() recursively calls itself to calculate all the divisors of x, using the vector factors[] and puts them in vector divisors[].
It can calculate divisors of any number which fits in int. Also it is quite fast.
Plenty of good solutions exist for finding all the prime factors of not too large numbers. I just wanted to point out, that once you have them, no computation is required to get all the factors.
if N = p_1^{a}*p_{2}^{b}*p_{3}^{c}.....
Then the number of factors is clearly (a+1)(b+1)(c+1).... since every factor can occur zero up to a times.
e.g. 12 = 2^2*3^1 so it has 3*2 = 6 factors. 1,2,3,4,6,12
======
I originally thought that you just wanted the number of distinct factors. But the same logic applies. You just iterate over the set of numbers corresponding to the possible combinations of exponents.
so int he example above:
00
01
10
11
20
21
gives you the 6 factors.
If you want all divisors to be printed in sorted order
int i;
for(i=1;i*i<n;i++){ /*print all the divisors from 1(inclusive) to
if(n%i==0){ √n (exclusive) */
cout<<i<<" ";
}
}
for( ;i>=1;i--){ /*print all the divisors from √n(inclusive) to
if(n%i==0){ n (inclusive)*/
cout<<(n/i)<<" ";
}
}
If divisors can be printed in any order
for(int j=1;j*j<=n;j++){
if(n%j==0){
cout<<j<<" ";
if(j!=(n/j))
cout<<(n/j)<<" ";
}
}
Both approaches have complexity O(√n)
Here is the Java Implementation of this approach:
public static int countAllFactors(int num)
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
for (int i = 1; i * i <= num; i+=1)
{
if (num % i == 0)
{
tree_set.add(i);
tree_set.add(num / i);
}
}
System.out.print(tree_set);
return tree_set.size();
}
//Try this,it can find divisors of verrrrrrrrrry big numbers (pretty efficiently :-))
#include<iostream>
#include<cstdio>
#include<cmath>
#include<vector>
#include<conio.h>
using namespace std;
vector<double> D;
void divs(double N);
double mod(double &n1, double &n2);
void push(double N);
void show();
int main()
{
double N;
cout << "\n Enter number: "; cin >> N;
divs(N); // find and push divisors to D
cout << "\n Divisors of "<<N<<": "; show(); // show contents of D (all divisors of N)
_getch(); // used visual studio, if it isn't supported replace it by "getch();"
return(0);
}
void divs(double N)
{
for (double i = 1; i <= sqrt(N); ++i)
{
if (!mod(N, i)) { push(i); if(i*i!=N) push(N / i); }
}
}
double mod(double &n1, double &n2)
{
return(((n1/n2)-floor(n1/n2))*n2);
}
void push(double N)
{
double s = 1, e = D.size(), m = floor((s + e) / 2);
while (s <= e)
{
if (N==D[m-1]) { return; }
else if (N > D[m-1]) { s = m + 1; }
else { e = m - 1; }
m = floor((s + e) / 2);
}
D.insert(D.begin() + m, N);
}
void show()
{
for (double i = 0; i < D.size(); ++i) cout << D[i] << " ";
}
int result_num;
bool flag;
cout << "Number Divisors\n";
for (int number = 1; number <= 35; number++)
{
flag = false;
cout << setw(3) << number << setw(14);
for (int i = 1; i <= number; i++)
{
result_num = number % i;
if (result_num == 0 && flag == true)
{
cout << "," << i;
}
if (result_num == 0 && flag == false)
{
cout << i;
}
flag = true;
}
cout << endl;
}
cout << "Press enter to continue.....";
cin.ignore();
return 0;
}
for (int i = 1; i*i <= num; ++i)
{
if (num % i == 0)
cout << i << endl;
if (num/i!=i)
cout << num/i << endl;
}
for( int i = 1; i * i <= num; i++ )
{
/* upto sqrt is because every divisor after sqrt
is also found when the number is divided by i.
EXAMPLE like if number is 90 when it is divided by 5
then you can also see that 90/5 = 18
where 18 also divides the number.
But when number is a perfect square
then num / i == i therefore only i is the factor
*/
//DIVISORS IN TIME COMPLEXITY sqrt(n)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
ll int n;
cin >> n;
for(ll i = 2; i <= sqrt(n); i++)
{
if (n%i==0)
{
if (n/i!=i)
cout << i << endl << n/i<< endl;
else
cout << i << endl;
}
}
}
#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define MOD 1000000007
#define fo(i,k,n) for(int i=k;i<=n;++i)
#define endl '\n'
ll etf[1000001];
ll spf[1000001];
void sieve(){
ll i,j;
for(i=0;i<=1000000;i++) {etf[i]=i;spf[i]=i;}
for(i=2;i<=1000000;i++){
if(etf[i]==i){
for(j=i;j<=1000000;j+=i){
etf[j]/=i;
etf[j]*=(i-1);
if(spf[j]==j)spf[j]=i;
}
}
}
}
void primefacto(ll n,vector<pair<ll,ll>>& vec){
ll lastprime = 1,k=0;
while(n>1){
if(lastprime!=spf[n])vec.push_back(make_pair(spf[n],0));
vec[vec.size()-1].second++;
lastprime=spf[n];
n/=spf[n];
}
}
void divisors(vector<pair<ll,ll>>& vec,ll idx,vector<ll>& divs,ll num){
if(idx==vec.size()){
divs.push_back(num);
return;
}
for(ll i=0;i<=vec[idx].second;i++){
divisors(vec,idx+1,divs,num*pow(vec[idx].first,i));
}
}
void solve(){
ll n;
cin>>n;
vector<pair<ll,ll>> vec;
primefacto(n,vec);
vector<ll> divs;
divisors(vec,0,divs,1);
for(auto it=divs.begin();it!=divs.end();it++){
cout<<*it<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
sieve();
ll t;cin>>t;
while(t--) solve();
return 0;
}
We can use modified sieve for getting all the factors for all numbers in range [1, N-1].
for (int i = 1; i < N; i++) {
for (int j = i; j < N; j += i) {
ans[j].push_back(i);
}
}
The time complexity is O(N * log(N)) as the sum of harmonic series 1 + 1/2 + 1/3 + ... + 1/N can be approximated to log(N).
More info about time complexity : https://math.stackexchange.com/a/3367064
P.S : Usually in programming problems, the task will include several queries where each query represents a different number and hence precalculating the divisors for all numbers in a range at once would be beneficial as the lookup takes O(1) time in that case.
java 8 recursive (works on HackerRank). This method includes option to sum and return the factors as an integer.
static class Calculator implements AdvancedArithmetic {
public int divisorSum(int n) {
if (n == 1)
return 1;
Set<Integer> set = new HashSet<>();
return divisorSum( n, set, 1);
}
private int divisorSum(int n, Set<Integer> sum, int start){
if ( start > n/2 )
return 0;
if (n%start == 0)
sum.add(start);
start++;
divisorSum(n, sum, start);
int total = 0;
for(int number: sum)
total+=number;
return total +n;
}
}