Printing the 1000th prime number - c++

#include <iostream>
using namespace std;
int main(){
int ctr = 0;
int count = 1; //Counts the nth prime number
int num = 3;
int div = 2; //Potential factors of the number
while(count <= 1000){
while(div < num){
if(num%div == 0){
ctr += 1; //If ctr is equal to 0, then num is prime
}
div += 1;
}
if(ctr == 0){ //If num is prime, count increases by 1
count += 1;
}
num += 1;
}
cout << num;
}
This is the code that I made to output the 1000th prime number. However, there must be something wrong with my program since it does not output 7919, which is the 1000th prime number.

It usually helps to refactor code like this into functions that have a clearly defined and testable behavior. For instance, the inner part of your code is a 'isPrime' function, and if you define it like this:
bool isPrime(int n) {
int div = 2; //Potential factors of the number
while (div < n) {
if (n % div == 0) {
return false;
}
++div;
}
return div == n;
}
It is easy to test, either through unit testing, or just manually checking if isPrime() works ok.
That makes the rest of the code more easy to write (and more importantly, read):
int primeCount = 0;
int n = 1;
while (primeCount < 1000) {
if (isPrime(n++)) {
++primeCount;
}
}
--n;
std::cout << n << std::endl;
As for why your code doesn't work. You should debug it. Go through line by line and see where it deviates from your expectations. Start out with finding the 3rd prime number, and not the 1000th.
Your isPrime part does not do what it is supposed to. Finding out why isn't hard, and you should definitely do that as a debugging-exercise, and not go with an easy answer from stackoverflow.

#include <stdio.h>
int main(){
int ctr = 0;
int count = 1; //Counts the nth prime number
int num = 3;
int div = 2; //Potential factors of the number
while(count <= 1000){
while(div < num){
if(num%div == 0){
ctr += 1; //If ctr is equal to 0, then num is prime
}
div += 1;
}
if(ctr == 0){ //If num is prime, count increases by 1
count += 1;
}
num += 1;
ctr=0;
div=2;
}
printf("%d",num);
}

Related

Converting an integer into it's binary equivalent

I have an assignment to make a program that should convert a number from it's integer value to a binary value. For some reason my array is always filled with zeroes and won't add "1"'s from my if statements. I know there are probably solutions to this assignment on internet but I would like to understand what is problem with my code. Any help is appreciated.
Here is what I tried:
#include <iostream>
/*Write a code that will enable input of one real number in order to write out it's binary equivalent.*/
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
while (number > 0) {
int i = 0;
if ((number / 10) % 2 == 0) {
binaryNumber[i] = 0;
}
if ((number / 10) % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 10;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
You need to remove number/10 in both the if statements. Instead, just use number. you need the last digit every time to get the ith bit.
Moreover, you need to just half the number in every iteration rather than doing it /10.
// Updated Code
int main() {
int number;
int binaryNumber[32] = { 0 };
std::cout << "Enter your number: ";
std::cin >> number;
int i = 0;
while (number > 0) {
if (number % 2 == 0) {
binaryNumber[i] = 0;
}
if (number % 2 != 0) {
binaryNumber[i] = 1;
}
number = number / 2;
i++;
}
for (int i = 31; i >= 0; i--) {
std::cout << binaryNumber[i];
}
return 0;
}
The first thing is the variable 'i' in the while loop. Consider it more precisely: every time you iterate over it, 'i' is recreated again and assigned the value of zero. It's the basics of the language itself.
The most relevant mistake is logic of your program. Each iteration we must take the remainder of division by 2, and then divide our number by 2.
The correct code is:
#include <iostream>
int main()
{
int x = 8;
bool repr[32]{};
int p = 0;
while(x)
{
repr[p] = x % 2;
++p;
x /= 2;
}
for(int i = 31; i >= 0; --i)
std::cout << repr[i];
return 0;
}
... is always filled with zeroes ... I would like to understand what is problem with my code
int i = 0; must be before the while, having it inside you only set the index 0 of the array in your loop because i always values 0.
But there are several other problems in your code :
using int binaryNumber[32] you suppose your int are on 32bits. Do not use 32 but sizeof(int)*CHAR_BIT, and the same for your last loop in case you want to also write 0 on the left of the first 1
you look at the value of (number / 10) % 2, you must look at the value of number % 2
it is useless to do the test then its reverse, just use else, or better remove the two ifs and just do binaryNumber[i] = number & 1;
number = number / 10; is the right way when you want to produce the value in decimal, in binary you have to divide by 2
in for (int i = 31; i >= 0; i--) { except for numbers needing 32 bits you will write useless 0 on the left, why not using the value of i from the while ?
There are some logical errors in your code.
You have taken (number/10) % 2, instead, you have to take (number %2 ) as you want the remainder.
Instead of taking i = 31, you should use this logic so you can print the following binary in reverse order:
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
Here is the code to convert an integer to its binary equivalent:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to convert integer to binary
void DecBinary(int n)
{
// Array to store binary number
int BinaryNumb[32];
int i = 0;
while (n > 0)
{
// Storing remainder in array
BinaryNumb[i] = n % 2;
n = n / 2;
i++;
}
// Printing array in reverse order
for (int j = i - 1; j >= 0; j--)
{
cout << BinaryNumb[j];
}
}
// Main Program
int main()
{
int testcase;
//Loop is optional
for(int i = 0; i < testcase; i++)
{
cin >> n;
DecToBinary(n);
}
return 0;
}

What does "not all control paths return a value" mean and how to troubleshoot. (C++)

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.

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))

C++ finding all prime numbers from 1 to a number entered

So the point is to have the program find and list all prime numbers between 1 and the number you enter. I'm using number_test as the number tested for prime, and divisor and the number to divide by.
I'm not sure what's wrong, as to me it looks functionally the same as the program posted here: Printing prime numbers from 1 through 100
with some minor changes (inputting a number, changing "i" to less than the number entered).
I've been looking for the past three or four days, and I haven't found anything that really answers this question fully, to the degree I need for class. Any help is much appreciated.
#include iostream
#include conio.h
using namespace std;
void main(void){
//Declare variables
int number_entered;
//Get inputs
cout << "This program lists all prime numbers from 1 through a positive number entered."
<< endl;
cout << "Please enter a positive integer."
<< endl;
cin >> number_entered;
cout << "Displaying all numbers from 1 to " << number_entered
<< endl
<< "Press any key to continue..."
<< endl;
getch();
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
getch();
}
You should use the Sieve of Eratosthenes to compute the primes less than n. Begin by making a list of all numbers from 2 to the maximum desired prime n. Then, at each iterative step, the smallest remaining number that hasn't yet been considered is output and all of its multiples are crossed off the list.
function primes(n)
sieve := makeArray(2..n, True)
for p from 2 to n step 1
if sieve(p)
output p
for i from p*p to n step p
sieve[i] := False
This O(n log log n) algorithm is very fast; you should be able to compute the 78498 primes less than a million in less than a second.
A simple C++ Program to find the "N" prime numbers.
#include <iostream >
using namespace std;
int main()
{
int N;
cin >> N;
for (int i = 2; N > 0; ++i)
{
bool isPrime = true ;
for (int j = 2; j < i; ++j)
{
if (i % j == 0)
{
isPrime = false ;
break ;
}
}
if (isPrime)
{
--N;
cout << i << "\n";
}
}
return 0;
}
Just a small suggestion. Since prime numbers are odd, even numbers can be left out.
For example, in below loops, i and j increase by 2 (i +=2) instead of by 1 (i ++).
for (int i=3;i<=numberByUser; i+=2){
for (j=3;j<=i;j +=2){
if (i%j==0){
break;
}
}
i think in your answer any way one time the loop will terminated(i am talking about the loop checking the whether it is prime or not)once it comes out you don't know whether it made the break or not.So try to make a flag variable and check outside.I ope that will work
for(n=lower+1; n<upper; n++)
{
prime = 1;
for(i=2; i<n; i++)
if(n%i == 0)
{
prime = 0;
break;
}
if(prime)
printf("\n\n\t\t\t%d", n);
}
for(int number_test = 2; number_test < number_entered; number_test++){
for(int divisor = 2; divisor < number_test; divisor++){
if(number_test % divisor == 0){
break;
}
else if(number_test % divisor != 0){
cout << number_test << " ";
break;
}
}
}
The above code will not show you the prime numbers, it will just show you the number you entered if/when you run into a divisor that is not a factor of the number. For example, if you enter "9", you will start at 2, which is not a factor of 9, so you will show "9" (incorrectly) as a "prime", when it is not.
The easiest method for testing if a number is a prime is by checking all prime numbers below it's square root to see if they are factors of the given number. If none of them are (then none of the non-prime numbers below the given number will be either), the number is a prime number. If it has at least one prime factor less than or equal to it's square root, it is not prime.
Since you are looking to show all primes in a range of [0, X], you can simply check your list of factors as you go along (or do it in reverse, which is effectively what the Sieve of Eratosthenes does).
When my point was like your one, I wrote this code, it worked. Hope it will help you.
#include <cstdio>
#include <vector>
using namespace std;
vector <int> sn;
bool isPrime(int n) {
if (n <= 1) {
return 0;
}
if (n == 2) {
return true;
}
if (!(n % 2)) {
return false;
}
for (int i = 2; i*i <= n; i++) {
if (!(n % i)) {
return 0;
}
}
return 1;
}
void primeNumbers(int k) {
sn.push_back (2);
int i = 3, j = 1;
for ( ; j < k + 1; i += 2 && j++) {
if (isPrime(i)) {
sn.push_back(i);
}
}
}
int main() {
int i, k;
scanf("%d", &k);
primeNumbers(k);
for (i = 0; i < sn.size(); i++) {
printf("%d ", sn[i]);
}
return 0;
}
int getNumberOfPrimes(int N) {
bool *numbers = new bool[N-1]();
for (int i = 2; i <= N/2; ++i) {
if (numbers[i-2] == true) continue;
for (int j = i+i; j <= N; j = j+i) {
numbers[j-2] = true;
}
}
int count = 0;
for (int i = 0; i < (N-1); ++i) {
if (numbers[i] == false) ++count;
}
delete []numbers;
return(count);
}
Man I guess I have the simplest methode of this all. Hope it works for you!
#include < iostream >
using namespace std;
int main()
{
int n, i, j
cin>>n; //The max limith
for(i=2; i<=2; i++)
{
for(j=1; j<=i/2; j++)
if(i%j!=o)
cout<<i;
}
return 0;
}
If a number has divisors, at least one of them must be less than or equal to the square root of the number. When you check divisors, you only need to check up to the square root, not all the way up to the number being tested.

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