I'm trying to find the prime factors of any given number through this code. This code is working perfectly for small numbers but for larger numbers(like 12345678), the program is not terminating. What's wrong??
using namespace std;
bool isPrime(int i)
{
for(int k=2;k<i;k++)
{
if(i%k==0)
{
return false;
}
}
if(i==1)
{
return false;
}
return true;
}
int main()
{
int n;
cout<<"Enter number"<<endl;
cin>>n;
for(int i=2;i<n;i++)
{
if(isPrime(i))
{
int x=n;
while(n%i==0)
{
cout<<i<<endl;
n=n/i;
}
n=x;
}
}
if(isPrime(n))
{
cout<<n<<endl;
cout<<1<<endl;
}
return 0;
}
You have a pretty good prime factoring algorithm here, except that you have overthought a few bits. The check if i is prime is only needed because you keep restoring n after you divide out the prime factors you find.
Remember that if you take your N and then divide all of the 2 factors out, then no even number is going to be a divisor of the remainder. In the same fashion, if you divide out the 3 factors, then no number divisible by 3 is going to be a divisor of the remainder.
Or in other words: If you count up from 2 and divide out all the divisors, then every divisor you find (in the remainder of N) must be a prime - because in order for a non-prime to be a divisor, that numbers prime factors must also be divisors, but all smaller primes have already been divided out.
Using that logic, I have cut a few superfluous parts of your algorithm out:
void printPrimes(int n)
{
for (int i = 2;i < n;i++)
{
//if (isPrime(i))
//{
//int x = n;
while (n % i == 0)
{
cout << i << endl;
n = n / i;
}
//n = x;
//}
}
//if (isPrime(n))
//{
cout << n << endl;
//}
}
If we clean that a bit, and change the outer loop condition a bit (so that the largest prime won't have to be printed after the loop), we end up with this:
void printPrimes(uint64_t n)
{
for (int i = 2;n > 1;i++)
{
while (n % i == 0)
{
cout << i << endl;
n = n / i;
}
}
}
Edit:
My point here was to point out that OP already got a pretty close to a good algorithm on his own (and for the size of number he posted this works really well), but as pointed out in comments it can still be done better. For example like this:
void printPrimes(uint64_t n)
{
while (n % 2 == 0)
{
std::cout << 2 << '\n';
n = n / 2;
}
for (uint64_t i = 3;i * i <= n;i += 2)
{
while (n % i == 0)
{
std::cout << i << '\n';
n = n / i;
}
}
if (n > 1)
std::cout << n << '\n';
}
I'm trying to create a function for an assignment that finds the two prime numbers that add up to the given sum. The instructions ask
"Write a C++ program to investigate the conjecture by listing all the even numbers from 4 to 100,000 along
with two primes which add to the same number.
Br sure you program the case where you find an even number that cannot be expressed as the sum of two
primes (even though this should not occur!). An appropriate message to display would be “Conjecture
fails!” You can test this code by seeing if all integers between 4 and 100,000 can be expressed as the sum
of two primes. There should be lots of failures."
I have created and tested the "showPrimePair" function before modifying it to integrate it into the main program, but now I run into this specific error
"C4715 'showPrimePair': not all control paths return a value"
I have already done my research to try to fix the error but it still
remains.
#include <iostream>
#include <stdio.h>
//#include <string> // new
//#include <vector> //new
//#include <algorithm>
using namespace std;
bool isPrime(int n);
//bool showPrimePair(int x);
//vector <int> primes; //new
const int MAX = 100000;
//// Sieve Sundaram function // new
//
//void sieveSundaram()
//{
// bool marked[MAX / 2 + 100] = { 0 };
// for (int i = 1; i <= (sqrt(MAX) - 1) / 2; i++)
// for (int j = (i * (i + 1)) << 1; j <= MAX / 2; j = j + 2 * i + 1)
// marked[j] = true;
//
// primes.push_back(2);
// for (int i = 1; i <= MAX / 2; i++)
// if (marked[i] == false)
// primes.push_back(2 * i + 1);
//}
// Function checks if number is prime //links to showPrimePair
bool isPrime(int n) {
bool prime = true;
for (int i = 2; i <= n / 2; i++)
{
if (n % i == 0) // condition for nonprime number
{
prime = false;
break;
}
}
return prime;
}
// Function for showing prime pairs ( in progress) Integer as a Sum of Two Prime Numbers
bool showPrimePair(int n) {
bool foundPair = true;
for (int i = 2; i <= n / 2; ++i)
// condition for i to be a prime number
{
if (isPrime(i) == 1)
{
// condition for n-i to be a prime number
if (isPrime(n - i) == 1)
{
// n = primeNumber1 + primeNumber2
printf("%d = %d + %d\n", n, i, n - i);
foundPair = true;
break;
}
}
}
if (foundPair == false) {
cout << " Conjecture fails!" << endl;
return 0;
}
}
// Main program in listing conjectures for all even numbers from 4-100,000 along q/ 2 primes that add up to same number.
int main()
{
//sieveSundaram();
cout << "Goldbach's Conjecture by Tony Pham " << endl;
for (int x = 2; x <= MAX; x++) {
/*if (isPrime(x) == true) { //works
cout << x << " is a prime number " << endl;
}
else {
cout << x << " is not a prime number " << endl;
}*/
showPrimePair(x);
}
cout << "Enter any character to quit: ";
cin.get();
}
First you can find all prime numbers in the desired range using the Sieve of Eratosthenes algorithm. Next, you can insert all found primes into a hash set. Finally for each number n in the range you can try all primes p that don't exceed n/2, and probe if the n-p is also a prime (as long as you have a hash set this operation is very fast).
Here is an implementation of Dmitry Kuzminov's answer. It takes a minute to run but it does finish within a reasonable time period. (Also, my implementation skips to the next number if a solution is found, but there are multiple solutions for each number. Finding every solution for each number simply takes WAAAAY too long.)
#include <iostream>
#include <vector>
#include <unordered_set>
std::unordered_set<long long> sieve(long long max) {
auto arr = new long long[max];
std::unordered_set<long long> ret;
for (long long i = 2; i < max; i++) {
for (long long j = i * i; j < max; j+=i) {
*(arr + (j - 1)) = 1;
}
}
for (long long i = 1; i < max; i++) {
if (*(arr + (i - 1)) == 0)
ret.emplace(i);
}
delete[] arr;
return ret;
}
bool is_prime(long long n) {
for(long long i = 2; i <= n / 2; ++i) {
if(n % i == 0) {
return false;
}
}
return true;
}
int main() {
auto primes = sieve(100000);
for (long long n = 4; n <= 100000; n+=2) {
bool found = false;
for (auto prime : primes) {
if (prime <= n / 2) {
if (is_prime(n - prime)) {
std::cout << prime << " + " << n - prime << " = " << n << std::endl;
found = true;
break; // Will move onto the next number after it finds a result
}
}
}
if (!found) { // Replace with whatever code you'd like.
std::terminate();
}
}
}
EDIT: Remember to use delete[] and clean up after ourselves.
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;
I'm trying to get all prime numbers in the range of 2 and the entered value using this c++ code :
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) {
result = i % b;
if (result == 0) {
result = b;
break;
}
}
cout << result<< endl <<;
}
}
the problem is that I think am getting close to the logic, but those threes and twos keep showing up between the prime numbers. What am I doing wrong?
I've fixed your code and added comments where I did the changes
The key here is to understand that you need to check all the numbers smaller then "i" if one of them dividing "i", if so mark the number as not prime and break (the break is only optimization)
Then print only those who passed the "test" (originally you printed everything)
#include <iostream>
using namespace std;
#include<iostream>
using namespace std;
int main()
{
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool isPrime = true; // Assume the number is prime
for (int b = 2; b < i; b++) { // Run only till "i-1" not "num"
result = i % b;
if (result == 0) {
isPrime = false; // if found some dividor, number nut prime
break;
}
}
if (isPrime) // print only primes
cout << i << endl;
}
}
Many answers have been given which explains how to do it. None have answered the question:
What am I doing wrong?
So I'll give that a try.
#include<iostream>
using namespace std;
int main() {
int num = 0;
int result = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
for (int b = 2; b <= num; b++) { // wrong: use b < i instead of b <= num
result = i % b;
if (result == 0) {
result = b; // wrong: why assign result the value of b?
// just remove this line
break;
}
}
cout << result<< endl <<; // wrong: you need a if-condtion before you print
// if (result != 0) cout << i << endl;
}
}
You have multiple errors in your code.
Simplest algorithm (not the most optimal though) is for checking whether N is prim is just to check whether it doesn't have any dividers in range [2; N-1].
Here is working version:
int main() {
int num = 0;
cin >> num;
for (int i = 2; i <= num; i++) {
bool bIsPrime = true;
for (int b = 2; bIsPrime && b < i; b++) {
if (i % b == 0) {
bIsPrime = false;
}
}
if (bIsPrime) {
cout << i << endl;
}
}
}
I would suggest pulling out the logic of determining whether a number is a prime to a separate function, call the function from main and then create output accordingly.
// Declare the function
bool is_prime(int num);
Then, simplify the for loop to:
for (int i = 2; i <= num; i++) {
if ( is_prime(i) )
{
cout << i << " is a prime.\n";
}
}
And then implement is_prime:
bool is_prime(int num)
{
// If the number is even, return true if the number is 2 else false.
if ( num % 2 == 0 )
{
return (num == 2);
}
int stopAt = (int)sqrt(num);
// Start the number to divide by with 3 and increment it by 2.
for (int b = 3; b <= stopAt; b += 2)
{
// If the given number is divisible by b, it is not a prime
if ( num % b == 0 )
{
return false;
}
}
// The given number is not divisible by any of the numbers up to
// sqrt(num). It is a prime
return true;
}
I can pretty much guess its academic task :)
So here the think for prime numbers there are many methods to "get primes bf number" some are better some worse.
Erosthenes Sieve - is one of them, its pretty simple concept, but quite a bit more efficient in case of big numbers (like few milions), since OopsUser version is correct you can try and see for yourself what version is better
void main() {
int upperBound;
cin >> upperBound;
int upperBoundSquareRoot = (int)sqrt((double)upperBound);
bool *isComposite = new bool[upperBound + 1]; // create table
memset(isComposite, 0, sizeof(bool) * (upperBound + 1)); // set all to 0
for (int m = 2; m <= upperBoundSquareRoot; m++) {
if (!isComposite[m]) { // if not prime
cout << m << " ";
for (int k = m * m; k <= upperBound; k += m) // set all multiplies
isComposite[k] = true;
}
}
for (int m = upperBoundSquareRoot; m <= upperBound; m++) // print results
if (!isComposite[m])
cout << m << " ";
delete [] isComposite; // clean table
}
Small note, tho i took simple implementation code for Sive from here (writing this note so its not illegal, truth be told wanted to show its easy to find)
#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! ☻