Console Application is not running and shows nothing - c++

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;

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;
}

code not executing due to huge time taken

Inputs n,m
I wrote this code which will find smallest number such that
no. will be divisible by n
and sum of its digits = m
but its not executing, its taking too much time and not showing any output
I tried to run i from n+1 to INT_MAX but its not making any difference
#include <iostream>
#include<climits>
#include<stdio.h>
using namespace std;
int main()
{
int n, m, a;
cin >> n >> m;
for (int i = n + 1; i < INT_MAX; i++)
{
a = 0;
if (i % n == 0)
{
while (i > 0)
{
a += i % 10;
i = i / 10;
}
if (a == m)
{
cout << a;
break;
}
}
if (a == m)
break;
}
}
I expect output to be some number but its showing nothing
Don't use i in while loop as you are using i in for loop already. Using i in while loop decremented its value by i/10 time, every time while loop is executed. Instead use any other local variable.
#include <iostream>
#include<climits>
#include<stdio.h>
using namespace std;
int main()
{
int n, m, a;
cin >> n >> m;
for (int i = n + 1; i < INT_MAX; i++)
{
a = 0;
if (i % n == 0)
{
int temp = i;
while (temp > 0)
{
a += temp % 10;
temp = temp / 10;
}
if (a == m)
{
cout << a;
break;
}
}
if (a == m)
break;
}
return 0;
}
**** EDIT
in your loop i is being incremented by 1 in each loop and then divided by 10 , therefore it is never truly increasing and neither is a, so it never reaches a hit and is stuck in a loop approaching positive 0

My code stops at a certain condition

In this code I input a test case number t and then input t numbers (n). Then my code prints the nth prime number. In the 1st line of the function, prime(), if I write if(a > 43000) return; Then the code works perfectly. But if I write if(a >= 165000) return; in the same place, codeblocks says the program has stopped working. But I can't understand why.
#include <iostream>
#include <cmath>
using namespace std;
int p[15000];
void prime(int a, int i)
{
if(a >= 165000) return;
else {
int q = 0;
int s=sqrt(a), d=3;
while(d<=s){
if(a % d == 0) {
q = 1;
}
d += 2;
}
if(q == 0) {
p[i] = a;
i++;
a += 2;
prime(a, i);
}
else {
a += 2;
prime(a, i);
}
}
}
int main()
{
p[0]=2;
prime(3, 1);
int k, T;
cin >> T;
for(int i = 1; i <= T; i++){
cin >> k;
cout << p[k - 1] << endl;
}
return 0;
}
First, I'll point out that your array p has only 15000 elements and that the 15001-th prime number is 163,847. This means that if you do a check for a >= 165000 before quiting you'll end up trying to fill indices of your array that are outside the bounds of your array.
Second, everyone is quite right that you should be careful when doing recursion. With each run of prime() you're allocating space for 5 new integer variables a, i, q, s, and d. This means you're allocating memory for tens of thousands of integers when (from the looks of your method) all you really need is 5.
Since it looks like these values are independent of all other iterations, you can employ a couple tricks. First, for q, s, and d by declaring them as globals they will only be allocated once. Secondly, by changing prime(int a, int i) to prime(int &a, int &i) you wont be allocating memory for a and i with each loop. This changes your code to look like the following:
#include <iostream>
#include <cmath>
using namespace std;
const int max_size = 15000 ;
int p[max_size];
int q ;
int s ;
int d ;
void prime(int &a, int &i)
{
if (i>=max_size) return ;
q = 0;
s=sqrt(a) ;
d=3;
while(d<=s){
if(a % d == 0) {
q = 1;
}
d += 2;
}
if(q == 0) {
p[i] = a;
i++;
a += 2;
prime(a, i);
}
else {
a += 2;
prime(a, i);
}
}
int main()
{
p[0]=2;
int a(3), i(1) ;
prime(a, i);
int k, T;
cin >> T;
for(int i = 1; i <= T; i++){
cin >> k;
// You should do a check of whether k is larger than
// the size of your array, otherwise the check on p[k-1]
// will cause a seg fault.
if (k>max_size) {
std::cout << "That value is too large, try a number <= " << max_size << "." << std::endl;
} else {
cout << p[k - 1] << endl;
}
}
return 0;
}
A couple of other changes:
instead of filling the array until you reach a specific prime number, I've changed your check so that it will fill the array until it hits the maximum number of entries.
I've also included a check as to whether the user has passed an index number outside the range of the "p" array. Otherwise it will produce a segmentation fault.
Now compiling this and running gives:
$ g++ prime_calc.cpp -o prime_calc
$ ./prime_calc
3
1500
12553
15000
163841
15001
That value is too large, try a number <= 15000.

How can I display only prime numbers in this code?

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)

Finding prime factors

#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! ☻