Error while solving Project Euler sum number 3 in C++ - c++

This is my code :
#include <iostream>
using namespace std;
int main()
{
long int x = 1;
long int res;
while (x<600851475143)
{
x++;
if(600851475143%x==0)
{
res=x;
cout<<x<<"\n";
}
}
}
I don't know whats wrong with it but it gives me this output :
839
1471
6857
59569
104441
486847
1234169
5753023
10086647
87625999
408464633
716151937
-716151937
-408464633
-87625999
-10086647
-5753023
-1234169
-486847
-104441
-59569
-6857
-1471
-839
-71
-1
Floating point exception
Process returned 136 (0x88) execution time : 156.566 s
Press ENTER to continue.
and when i substitute 600851475143 with 13195 [ which was in the example ]...
it works fine...and gives me this output :
5
11
55
11149
Process returned 0 (0x0) execution time : 0.005 s
Press ENTER to continue.
I don't know what i am doing wrong... :/
Perhaps my previous program didn't run properly...i tried it with int in the beginning and then changed it to long int...No difference...

Negative values are due to overflow. Start by using unsigned integers instead of signed integers. In addition to that, in 32 bit computers, long int and int types are both 32 bits.
unsigned long long int x = 1;
unsigned long long int res;
Also, you could emphasize the fact that those constants are unsigned
while (x<600851475143U)
{
x++;
if(600851475143U%x==0)
{
res=x;
cout<<x<<"\n";
}
}

When your positive number suddenly turns negative after ++, it's a sure sign of integer overflow. You need to pick a data type that is capable of holding larger integers, e.g. long long.
On a side note, your algorithm is not searching for the largest prime factor, as required in the problem. It searches for the largest factor, which is not necessarily a prime one.
By the way, if you can prove that stopping the search upon reaching the square root of the number being factored is correct, you could speed up your program a great deal.

Your variable types can't hold 12-figure numbers. Typical unsigned long int can store from 0 to 4,294,967,295, for signed - −2,147,483,648 to 2,147,483,647.

try using an unsigned long long, it should store at least 18,446,744,073,709,551,615 (which number I can't even imagine).

The code below will show all the prime factors of a number entered by user.But 600851475143 is a too much big number to find its prime factors. Modify this program to see 600851475143's prime factors and also modify it to find out the greatest prime factor of them. I have learned c++ for two months only, so i can help you this much only.All the best.
#include<iostream.h>
#include<conio.h>
class primefactor
{
unsigned long int a;
public:
void factor();
};
void primefactor::factor()
{
cout<<"Enter any number to see its prime factors";
cin>>a;
int count=0;
int count1=0;
for(unsigned long int loop1=a;loop1>=1;loop1--)
{
if(a%loop1==0)
{
for(unsigned long int loop=loop1;loop>=1;loop--)
{
if(loop1%loop==0)
{
count++;
}
}
if(count==2)
{
count1++;
cout<<loop1<<"\t";
}
}
count=0;
}
cout<<"\n"<<"There are"<<count1<<"\t"<<"prime factors";
}
void main()
{
primefactor k;
clrscr();
k.factor();
getch();
}

Related

Why by using n&(n-1) is not able to calculate number of 1's bits?

I found a video on youtube that says by using n&(n-1) we can able to count number of 1's bits and it's much faster than - right shifting the bits by one and then checking the last bit . When I wrote the code using this method to calculate number of bits it's giving output as 9 instead of 3 - if we 01011 as parameter.
I debug the program and not able to find why it's happening so ?I am confused when in while loop condition , both A and A-1 is 512, it get out of loop even A&(A-1) = 1000000000 not 0 (zero).
If anyone knows what I am missing please let me know .
#include <iostream>
using namespace std;
int bits(unsigned int A){
int counter=0;
unsigned int t;
while (A&(A-1))
{
counter++;
A--;
}
return counter;
}
int main()
{
unsigned int A=01011;
int res=bits(A);
cout<<"Result is "<<res<<"\n";
return 0;
}
Thanking You
Yours Truly,
Rishabh Raghwendra
This is the Kerningham trick to calculate the number of bits without shifting. (Original author precedes Kerningham by a decade, but mr K popularised it).
n&(n-1) peels off the least significant one, meaning that one should write the result back to n.
while (n) {
++counter;
n&=n-1;
}

Inconsistency with std::cout - failing to print on specific numbers

I'm running a program to factorise a large number, which outputs each factor it finds as it goes through, smallest to largest. It works fine for numbers below the 1 billion mark, as far as I have tested, but I get a very strange bug when I input 1185914148403 to the program - the factor of 311 will not print.The modulus division returns 0, and it enters the inner while loop, but it won't print 311 unless I explicitly check for that case. For low values, like 622, 311 prints just fine, but here, the smaller factors print, and everything except the printing works fine, and yet nothing is printed. What could possibly be going on?
#include <iostream>
#include <vector>
#include <ctime>
#include <string>
void nextPrime(std::vector<long long>& primes);
int main(int argc,char* argv[])
{
int startTime=clock();
long long num=std::stol(argv[1]);
long long largest=1;
std::vector<long long>primes;
primes.push_back(2);
while(1) //iterate through the prime list, divide the num down as far as pos - done when num=1
{
long long prime=primes[primes.size()-1]; //the largest prime, the one we care about
while(!(num%prime)) //while that prime divides, divide down
{
num/=prime;
largest=prime;
std::cout<<std::endl<<prime;
if(prime==311)
{
//std::cout<<std::endl<<prime;
}
}
if(num==1) //once we divide down by the largest prime factor, it'll hit 1, and we're done
{
break;
}
nextPrime(primes);
long long newPrime=primes[primes.size()-1];
if(newPrime>num)
{
break;
}
}
int endTime=clock();
double timeTaken=(endTime-startTime)/double(CLOCKS_PER_SEC);
std::cout<<"\nThat took "<<timeTaken<<" seconds\n";
std::cout<<"The largest prime factor of "<<std::stol(argv[1])<<" is "<<largest<<"\n";
}
void nextPrime(std::vector<long long>& primes)
{
long long largest=primes[primes.size()-1];
long long maybe=largest+1;
long long pt=0;
while(1)//check all the primes up to sqrt of the maybe-prime
{
long long prime=primes[pt];
if(prime*prime>maybe)
{
primes.push_back(maybe);
return;
}
if(!(maybe%prime)) //if the prime is a factor, it's not prime-try next, and go back to 1st prime
{
maybe++;
pt=0;
continue;
}
else //if not, check the next prime
{
pt++;
}
}
}
You write:
std::cout<<std::endl<<prime;
Maybe you meant:
std::cout << prime << std::endl;
This will print the prime and then flush the output. For the number 1185914148403, there is an early factor 311 and then no more factors for a while.
Your algorithm is very slow and takes a long time before it finds any other factor. Since you did not flush the output after outputting the first 311, then depending on your compiler, you may not have that number appear on screen for a very long time.
As noted in comments, std::stol returns a long, however your program works with long long. Since you did not get an out-of-range exception thrown, this indicates that you are on a system where long is 64-bit. But it would be good to fix this anyway and use std::stoll.

which data type should we use for taking input a number which is in between 0<= number <= 10^18

in this below code , i am getting run time error , i want to input a number which is in between 0<= a <= 10^18 , a is number , also which data type should we use for taking such a big number like 10^18 , help
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
main()
{
int flag=1,cases;
long int j,i;
unsigned long long int a;
cin>>a;
if(a==0)
{
cout<<"yes";
}
else
{
unsigned long long int temp[a];
temp[0]=0;
cases=1;
i=1;
while(temp[i]!=a)
{
if(cases==1)
temp[i]=temp[i-1]+1;
else if(cases==2)
temp[i]=temp[i-1]+2;
else if(cases==3)
temp[i]=temp[i-1]+3;
cases++;
if(cases>3)
cases=1;
i++;
}
for(j=0;j<i;j++)
{
if(temp[j]==a)
{
cout<<"yes";
break;
}
if(j==i-1)
flag=0;
}
if(flag==0)
cout<<"no";
}
}
You are using temp without initializing it. You do set the first element to zero but then you start iterating from 1. Furter how should temp of any index be to equal a? Unlikely - so your while will not terminate. Sooner or later you will get a run time error.
Try adding
temp[a-1] = a;
Before the while loop
Or perhaps you actually want the while to be
while(i <a)
You're already using a unsigned long long int, which is large enough for 18446744073709551615 (2^64 - 1) or greater*
http://www.cplusplus.com/reference/climits/
My guess is your runtime error is resulting from something other than this.
Be wary of using a variable length array though. Think about how much memory it would take to allocate 10^18 unsigned long long int's for your array? Assuming that it maps to a 64 bit type : 8 bytes per * (10^18) is ~ 7105 PetaBytes.
Let's say you are using unsigned long long int vector.
vector<unsigned long long int> temp ;
if you write cout<<temp.max_size(); it will give you how many elements vector can theoretically manage depending on your machine(((e.g. if you write the same in computer where RAM is bigger, it will give you another number))).It doesn't know how much memory will actually be available when you run the program.Let's say max_size() gives us some number,578910255011, So let's say your a=10^10, unsigned long long = 8 byte,(10^10*8)/1024/1024/1024 = 9.31GB. So your RAM should be equal to 9.31Gb, that's why it's a runtime error, because RAM is the memory used by running programs. So to solve this problem you should either increase your RAM which for 10^12 unsigned long long elements=931Gb and would cost a fortune :) (if your computer can even support that much) or use something like STXXL

Online judge Rejecting My Answer

The Next Palindrome
The below code is the solution to this problem
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
Input
The first line contains integer t, the number of test cases. Integers K are given in the next t lines.
Output
For each K, output the smallest palindrome larger than K.
Example
Input:
2
808
2133
Output:
818
2222
#include <iostream>
using namespace std;
int main()
{
long t;
cin>>t;
long a[t],k;
for(long i=0;i<t;++i)
{
cin>>k;
a[i]=k;
}
for(long i=0;i<t;++i)
{
long palin=0,num;
palin=a[i];
num=palin+1;
while(1)
{
long x=0,rev=0,ans=num;
do
{
x=ans%10;
rev=rev*10+x;
ans=ans/10;
}while(ans);
if(rev==num)
{
cout<<"\n"<<rev<<"\n";
break;
}
else
++num;
}
}
return 0;
}
The code is giving me expected output, I even made changes in the code making the variable K and t to LONG, should i make them long long instead of long, or is there any issue with my logic ...?
You can write a effective program by using a string instead of long. I have used it. Here I am giving the code:
#include<iostream>
using namespace std;
#include<string.h>
int main()
{
char s[80]; //you can take any big index instead 80
gets(s);
int a=0,l=strlen(s);
for(int i=0;i<l;i++) {
if(s[i]==s[l-i]) {
a++;
}
}
if(a==l) {
cout<<"Number is palindrome";
}
else {
cout<<"Number is not palindrome";
}
return(0);
}
Is the task really to handle integers up to 1,000,000 digits? Or is the input smaller than 1M?
"long" is guaranteed to be at least 32 bits long (so an unsigned long can hold integers [0, 4,294,967,295]. So if your input is < 1M, your safe with just regular long.
"long long" is guaranteed to be at least 64 bits long, so the range for unsigned long long is [0, 18x10^18]. Larger than 4M but still much smaller than 1M decimal digits.
Another issue with your code is the fact that it looks like your trying to dynamically allocate a stack array.
cin>>t;
long a[t],k;
You can't provide a variable as the array size. This is a very basic point an C++, and you must do one of the following:
Use a constant compile-time maximum size for the array (simplest solution).
#define A_MAX_SIZE 100
long a[A_MAX_SIZE];
Use a dynamic array (but then you must allocated and delete it later).
See link: http://www.cplusplus.com/doc/tutorial/dynamic/
Use an STL container that will take care of memory for you.
For example: http://www.cplusplus.com/reference/stl/vector/vector/

Prime number programs stops at 20,031'st prime, 225,149 for no apparent reason. No error message

Why does my program for finding primes work, but exit at the 20,031'st prime, which is 225,149? There is no error message and x-code claims that the program "ended with exit code" as it would normally do.
My question is not about the program per se, which appears to be working (finding primes), but what limit or calculation error I'm coming up against that's causing it to exit.
This loop is intentionally infinite, but it prints out to 225,149 as expected then stops and exits with no error. It just exits, as if it reached the end of a loop. I've tried putting a limit on iterations and bumped it up bit by bit to 10,000,0000,000 but it oddly stops a the same number, 225,149.
Is there a computation time bound that is exceeded or something else?
The last bit of output: the program outputs the a count of the primes from zero, then the prime.
20027) 225109
20028) 225119
20029) 225133
20030) 225143
20031) 225149
Program ended with exit code: 0
#include <iostream>
#include <cmath>
using namespace std;
//performs modulus and find remainder return remainder r to void primal
double fmodulus (double n, double d)
{
double r;
r= fmod(n, d);
return r;
}
//finds prime number using modulus double type modulus function fmod()
void primal()
{
int count=1;
double n=3.0, d=2.0;
for (int i= 0; i>=0; ++i)
{
double r;
r= fmodulus(n, d);
//if n==d then is prime nymber
if (n==d)
{
cout<<count<<") "<<n<<endl;
n++;
d=2.0;
count++;
}
//if remainder == 0 then not prime number
else if (r==0)
{
n++;
d=2.0;
}
//not prime so updates d of modulus increment by 1
else
{
d++;
}
}
}
int main(int argc, const char * argv[])
{
cout<<endl;
primal();
}
The problement si that i is incremented each time you make a test. In this case, you can easily reach 2 billion tests. And when i overflows, its value becomes negative, so the loop ends.
You can do 3 different things to solve this problem :
The first is to change the type of i to make it unsigned int or unsigned long long. Those types are always positive, and your loop will never end. The difference is only that an unsigned long long is written on 64 bits instead of 32.
The second way is to change the condition in your loop ; if you want it to be infinite, you can simply use 1. This is the general true condition.
The last way is to change your program, inserting a second loop inside the first to ensure that a different number is tested at each iteration.
Eventually the int i will overflow. Signed integer overflow is undefined behavior so the compiler can do whatever it wants.
Usually it will just overflow to INT_MIN, which is negative so your loop ends.
Try making i be a long and print its value to monitor it.