So I'm trying out Problem 7 of Project Euler.
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int a){
if (a==2||a==3){
return true;
}
if (a%2==0){
return false;
}
bool prime=true;
for (int b=2;b<sqrt(a);b++){
if (a%b==0)
prime=false;
}
if (prime==true)
return true;
else
return false;
}
int main(){
int infinite=0;
long long int primecounter=0;
for (int c=2;infinite==0;c++){
if (isPrime(c)==true){
primecounter++;
//cout<<c<<endl;
if (primecounter==10001)
{cout<<c;
break;}
}
}
return 0;}
This is what I've come up with so far. It works for the few numbers that I tested, like the 6th prime number etc. However, when I run it for the 10001st prime, it gives me 104021, and the answer is wrong. Can someone tell me what is wrong with my code?
Where you get it wrong is b < sqrt(a). Think of a=25, what happens in this case?
rest of answer already pointed by comments.
Although this is not required for this specific problem, you should take a look at Sieve of Eratosthenes algorithm. You will need it sooner or later to solve prime related problems.
You can solve it without getting help from 'cmath' too.Logic is like...
To check whether a number is prime, set a counter variable to 0; write a loop to divide the number by every number less than it till 1. If a number completely divides it, the counter will increase by one; the counetr will be exactly 2 for a prime number.
To calculate sucha big number u should choose a proper datatype too.I have used 'long long int' as a datatype.
My code for the project euler problem no 7 is as follows.Hope it helps you.Best wishes.Editions and improvements in this program are most welcome.Only bug is the time that it consumes,it takes more than an hour to reach the 10001th prime number.
#include<iostream.h>
#include<conio.h>
class prime
{
long long int a;
long long int j,i;
public:
void display();
};
void prime::display()
{
j=0;
long long int count=0;
long long int count1=0;
while(count1!=10001)
{
j=j+1;
i=j;
while(i!=0)
{
if(j%i==0)
{
count++;
}
i--;
}
if(count==2)
{
count1++;
cout<<count1<<"\t"; //The serial number of the prime number.
cout<<j<<"\t";// This will diaply all prime numbers till 10001.
}
if(count1==10001)
{
cout<<"\nThe 10001th prime number is:"<<j;
}
count=0;
}
}
void main()
{
prime k;
clrscr();
k.display();
getch();
}
Related
I was trying this question.
The prime factors of 13195 are 5, 7, 13 and 29.What is the largest prime factor of the number 600851475143 ?
And I had written the following code:
#include<iostream>
#define num 600851475143
using namespace std;
int isprime(unsigned long long int n)
{
unsigned long long int c=0;
for(unsigned long long int i=2;i<n;i++)
{
if(n%i==0)
{
c++;
break;
}
}
if(c==0)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
unsigned long long int a,i,n=num;
while(n-- && n>1)
{
if(isprime(n)==1 && num%n==0)
{
cout<<n;
break;
}
}
return 0;
}
The problem occurring with the code is it is working for 13195 and other small values. But not getting any output for 600851475143. Can anyone explain why it is not working for large value and also tell the changes that should be made in these to get the correct output.
The below code snippets are from c (but should run quite nice with c++ as well):
#include <stdio.h>
#define uIntPrime unsigned long long int
#define uIntPrimeFormat "llu"
uIntPrime findSmallestPrimeFactor(uIntPrime num)
{
uIntPrime limit = num / 2 + 1;
for(uIntPrime i=2; i<limit; i++)
{
if((num % i) == 0)
{
return i;
}
}
return num;
}
uIntPrime findLargestPrimeFactor(uIntPrime num)
{
uIntPrime largestPrimeFactor = 1; // start with the smallest possible value
while (num > 1) {
uIntPrime primeFactor = findSmallestPrimeFactor(num);
if (primeFactor > largestPrimeFactor) largestPrimeFactor = primeFactor;
num = num / primeFactor;
}
return largestPrimeFactor;
}
How can this work?
(first function:) Counting the numbers up from 2 means you are starting with prime factors on the lower end. (Numbers that are non-prime when counting are just not working out as fraction-less divisors and at the same time their prime number factor components were already probed because they are lower.)
(second function:) If a valid factor is found then the factor is pulled out from the number in question. Thus the search for the now smallest prime in the pulled-out number can repeat. (The conditional might probably be superfluous due to lower numbers are found first anyway - but it might resemble a search pattern you are familiar with - like in a minimum/maximum/other-criteria search. I am now leaving it up to you to proof it right or wrong with testing with your own main routine.)
The stop condition is about having the last factor extracted means dividing the value by itself and getting a value of 1 for num.
(There is for sure still much space for speeding this up!)
First of all, I would clarify that I am new to programming and started with c++ recently. There was a problem related to Legendre's formula in my math textbook and I thought about making a program related to it. It takes a number from user n, and finds the highest power of n which divides n!
It runs fine for a lot of numbers but messes up for a few others and it is completely random. This is a snippet from the code.
#include <iostream>
#include <math.h>
using namespace std;
int prime(int);
int calc(int, int);
int main()
{
int n;
int hpf=2;
cout<<"This program finds highest power x that divides x!"<<endl;
cout << "Enter number : " << endl;
cin>>n;
for(int i=2; i<=n; i++)
{
bool p=prime(i);
if(p==true && n%i==0)
hpf=i;
}
cout<<"The highest prime factor of the number is : "<<hpf<<endl;
int p=calc(hpf, n);
cout<<"The highest power of "<<n<<" that divides "<<n<<"!"<<" is : "<<p;
return 0;
}
calc(int f, int n)
{
int c=0 , d=1, power=1, i=0;
while(i>=0)
{
int x= pow(f,power+i);
if(i>0 && n%x==0)
d++;
if(x<=n)
{
c+=n/x;
i++;
}
else
break;
}
return c/d;
}
prime(int n)
{
bool isPrime = true;
for(int i = 2; i <= n/2; i++)
{
if (n%i == 0)
{
isPrime = false;
break;
}
}
return isPrime;
}
I pass the highest prime factor of n and the number n itself to int calc(int, int).
Now here is the problem:
when I input n=9, I get
Enter number :
9
The highest prime factor of the number is : 3
The highest power of 9 that divides 9! is : 2
on the other hand, if I input 25, I get
Enter number :
25
The highest prime factor of the number is : 5
The highest power of 25 that divides 25! is : 6
This is clearly wrong, the highest power should be 3.
It also works for bigger numbers accurately, but not all.
PS: I use codeblocks.
I'm not sure why exactly it works for 9 and not for 25(your program seems fine, but you probably have a problem when you calculate d or something), although both are squares of primes and your code seems to take care of that, but I do know why it doesn't work with number like 12. This happens because your code only looks at the highest prime factor and ignores the others. This will give you the true result when the other prime factors appear less frequently then the biggest one, but in all other cases this assumption leads to wrong results, because the highest is then also limited by smaller primes. So a correct solution has to take care of all prime factors.
For that you first need to factor the number(getting the prime factors and their power!). You can just google that if you are unsure how to do that. I don't want to include it here because then the answer would get to long.
Then you need to find how often the number is present in the factorial.
As you already know(at least you used it in your code) you can count by summing up the occurence as a factor of each power of the prime in every factor of the factorial which can be done through division like this:
n/p¹ + n/p² + n/p³ + n/p⁴ + …
That can be put into a simple function(using a simple self-made power calculation):
int occurenceInFaculty(int factor, int faculty) {
int sum = 0;
for(int power = factor; power <= faculty; power *= factor) { // Go through all powers
sum += faculty/power;
}
return sum;
}
Now you can calculate the occurrence for each of the prime factors of your number and if you divide by the power of that prime factor in the factorization you get an upper limit for the highest power.
Then all that's left to do is take the minimum over all prime factors and you are done.
Assuming one possible way of storing the prime factorization here is what the resulting code could look like:
Somewhere in the beginning of your code:
typedef struct {
int prime;
int power;
} PrimeFactor;
Assuming a prime factorization method like this:
PrimeFactor* factorization(int number, int* factors) {
// Factorize here. Return a pointer to an array of PrimeFactors and set the pointer factors to the arrays length.
}
And then the calculation part:
int number = 25; // Put your number here.
int length = 0;
PrimeFactor* factors = factorization(25, &length);
int min = number; // Some reasonable upper border because n! < n^n
for(int i = 0; i < length; i++) {
if(occurenceInFaculty(factors[i].prime, number)/factors[i].power < min)
min = occurenceInFaculty(factors[i].prime, number)/factors[i].power;
}
This program also gets 25 right!
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Can anyone help me optimize my code as it is showing Time limit exceeded even after i am using sieve. Here is the link to the problem
https://www.spoj.com/problems/PRIME1/
Here is my code:
#include <iostream>
#include <math.h>
using namespace std;
int is_prime(int m)
{
int i,c=0;
for(i=2;i<=sqrt(m);i++)
{
if(m%i==0)
c++;
}
if(c==0)
return 1;
else
return 0;
}
int main()
{
int n,m,i,j,k,num;
cin>>num;
for(i=1;i<=num;i++)
{
cin>>m>>n;
int a[n];
for(j=0;j<=n;j++)
a[j]=1;
for(j=m;j<sqrt(n);j++)
{
if(is_prime(j)==1)
{
for(k=j*j;k<=n;k=k+j)
{
a[k]=0;
}
}
}
for(j=m;j<=n;j++)
{
if(a[j]==1)
cout<<j<<endl;
}
cout<<endl;
}
enter code here
return 0;
}
Your code has few issues:
You cannot create 10^9 (int a[n] ) array in given time constraint!
The nested for loops are taking too long almost O(sqrt(n-m)^2)
To optimise use https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes and https://www.geeksforgeeks.org/segmented-sieve/
Im trying to solve this problem on programing.
Here is the question.
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
Now I've cooked up a c++ program, which tries to check it by brute force, however, while executing its stuck at 5. Here is the Program
#include <iostream>
#include <math.h>
using namespace std;
const long long no = 600851475143;
long long isprime(long long p)
{
long long reply = -1;
long long i = 2;
while (i < pow(p, 0.5)) {
if (i % p == 0)
reply = i;
}
if (reply == -1){
return 0;
cout<<" yup its prime "<<endl;
}
else
return reply;
}
long long factor(long long x)
{
for (long long i = 2; i < no; i++) {
cout<<"Trying "<<i<<endl;
if ((isprime(i) == 0)&& (no % i == 0)) {
return i;
cout<<"found "<<i<<endl;
break;
}
}
}
int main()
{
long long ans = no;
while (ans != 1) {
cout << factor(ans) << endl;
ans = ans / factor(ans);
}
}
and this is the output
~/Desktop/proj$ ./a.out
Trying 2
Trying 3
Trying 4
Trying 5
I really don't understand why its stuck at number 5, can someone help me out?
EDIT : Thanks b13rg , I realised my mistake . I now have a better algorithm , I have pasted it down for anybody needing it.
#include<iostream>
#include<math.h>
using namespace std;
long long fun (long long x)
{
for(long long i=2; i<sqrt(x);i++){
while (x%i==0){
cout<<i<<endl;
x=x/i;
}
}
}
int main(){
fun(600851475143);
return 0;}
You seem to never change the value of i or p in the while loop in the function isprime. It fails because sqrt(5) is larger than 2, and nothing in the while loop ever changes.
For the problem you're trying to solve:
You could first optimize the checking loop by only trying odd numbers, so first do 2, then 3, then 5 etc. To make it even faster you could hard code in the first few primes, but that might be beyond the scope of this project.
To find the largest prime factor, you would want to first find the smallest prime factor. For example, in the number above, the smallest is 5. The next step would be to divide 13195 by 5 to get 2369. Then start again to find the smallest prime factor of this number, and keep going until the dividing result is prime.
Number|Smallest prime
------|--------------
13169 | 5
2369 | 7
377 |13
29 |Largest prime factor of 13169
I recently stumbled on this Project Euler Problem #25:
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?
I just know C++98 and no other programming language. I have tried to solve it, making changes to get support of c++11.
Working:
#include <iostream>
#include<cstdio>
long len(long); //finding length
int main()
{
/* Ques: What is the first term in fibonacci series to contain 1000 digits? */
int ctr=2;
unsigned long first, second, third, n;
first=1;
second=1;
std::cout<<"\t **Project EULER Question 25**\n\n";
for(int i=2;;++i)
{
third=first+second;
// cout<<" "<<third;
int x=len(third);
// cout<<" Length: "<<x;
// cout<<"\n";
first=second;
second=third;
ctr++;
if(x>1000) // for small values, program works properly
{
std::cout<< " THE ANSWER: "<< ctr;
system("pause");
break;
}
}
}
long len(long num)
{
int ctr=1;
while(num!=0)
{
num=num/10;
if(num!=0)
{
ctr++;
}
}
return(ctr);
}
I know this is brute force, but can i make it more efficient so that i get the answer ?
Any help will be greatly appreciated.
EDIT:
By using Binet's Formula, as suggested by PaulMcKenzie and implementing it as:
#define phi (1+sqrt(5))/2
int main(void)
{
float n= ((999 + (1/2)*log10(5))/(log10(phi))); //Line 1
cout<<"Number is : "<<n;
return 0;
}
Output: 4780.187012
Changing Line 1, above, to :
float n= ((999 + log10(sqrt(5)))/(log10(phi)));
OUTPUT: 4781.859375
What could be possibly the error here?
unsigned long simply can't hold 1000-digit number. So you will get the overflow in your code when first and second will reach the unsigned long limit. If you want a brute force solution - consider use of something like biginteger library or write one by yourself.