prime path using bfs - c++

I was solving a question prime path
I am using bfs to solve this question
Here is my solution https://ideone.com/GMOyWX
when i am using this function to check for prime ,I am getting correct answer as 6
bool isprime(int number) {
for (int i = 2; i < sqrt(number); i++) {
if (number % i == 0 && i != number) return false;
}
return true;
}
But when I am using sieves I am getting wrong answer as 5
void sieves(int n) {
isPrime[0] = false;
isPrime[1] = false;
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
for (int j = 2*i; j <= n; j+=i) {
isPrime[j] = false;
}
}
}
}
can anyone tell me whats wrong with the sieves?

I think you sieve implementation is correct, so you are doing something wrong in any other place. from your code i see that you are calling your sieve function for every test case. This should not be necessary. In problem statement there is clearly stated that input will be 4 digit two number, so in maximum case, 100000 should be enough limit to generate checking vector if every number is prime or not.
So just call once your sieve with 100000 once. Prime numbers are fixed number.

Related

simple function for finding the next prime number using a while loop in c++

first post here so hello world lol.
i starting learning c++ and doing some challenges. One i found is "find the next prime number" given an integer, make a function to find the next sequential prime number eg if given 12 return 13, if given 24 return 29, if given a prime return that. I dont understand why the following block of code doesnt work (my guess is that two of the conditions
int nextPrime(int num) {
while (num % 2 !=0 && num %3 != 0 && num %4 != 0 && num %5 != 0 && num %6 != 0 && num %7 != 0 && num %8 != 0 && num %9);
++num;
return num;
}
its a relatively easy task, but the fact i dont know why its not working bothers me more than the fact it isnt working. Any help you lovely internet people can provide is most welcome.
bool PrimeNumber(int n)
{for(int i=2;i<=n;i++){
if(n%i==0){
return false
}
return true
}
what you want to do is check each number starting from the next one to given number, see if it is prime. then just return the first one to be prime.
in nextPrime() function, we take a number starting from the next one to given number.
then in isPrime(), check if it is a prime.
if it is, return the number. else continue with the next one.
bool isPrime(int n)
{
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
int nextPrime (int n){
for (int i=n+1; i<1000000; i++){
if (isPrime(i)) return i;
}
}
#include <bits/stdc++.h>
using namespace std;
//check if number is prime divide by all number less than sqrt(n)
bool isprime(int n){
for(int i=2;i*i<=n;i++){
if(n%i==0){
//not a prime return false then.
return false;
}
}// its a prime number.
return true;
}
int main() {
int n = 12345;
while(1){
if(isprime(n)){
cout << n <<endl;
// id its a prime number we are done break the loop.
break;
}
// increase n by 1. continue the loop untill the next prime.
n+=1;
}
return 0;
}

Determining prime number

Im doing exercise from the Bjarne Stroustrup book called "Programming principles and practice using c++". I have to find first n prime numbers that user wants[user enters 5, and program finds first five prime numbers]. I found the solution on this site:
http://people.ds.cam.ac.uk/nmm1/C++/Exercises/Chapter_04/ex_15.cpp
bool prime (vector<int> table, int number) {
for (int i = 0; i < table.size(); ++i)
if (number%table[i] == 0) return false;
return true;
}
but i cant understand the test for primality. Why modulo? I have my own test for primality and its much easier to understand for me, albeit its less elegant and more verbose.
bool isPrime(int num) {
for (int i = 2; i < num; i++) {
for (int j = 0; j < num; j++) {
if (i*j == num) {
return false;
}
}
}
if (num == 1) {
return false;
}
return true;
}
So if anyone can explain me that guy code i would be greatful.
Here's the other code, included in its entirety:
#include "std_lib_facilities.h"
bool prime (vector<int> table, int number) {
for (int i = 0; i < table.size(); ++i)
if (number%table[i] == 0) return false;
return true;
}
int main () {
int count, next;
cout << "Input the number of primes\n";
cin >> count;
vector<int> table;
next = 2;
while (table.size() < count) {
if (prime(table,next)) table.push_back(next);
++next;
}
for (int n = 0; n < table.size(); ++n)
cout << table[n] << " ";
cout << endl;
// keep_window_open();
return 0;
}
This code populates the vector table with all the prime numbers it has found so far. Starting from 2, it checks if the number is divisible by any of the numbers in this table it has constructed. If it isn't divisible, it means that this number is a prime, and it gets entered into the table.
The modulo operator is used to check for divisibility here. a%b returns the remainder that occurs when the division a/b is performed. If this value is 0, there is no remainder, and we can conclude that a is divisible by b.
The modulo operator returns the remainder of a division operation. So if the remainder is equal to 0 for any of the numbers in the table, then we can say that the number is evenly divisible, and therefore not prime. On the other hand, if the modulo returns anything other than 0 for all of the numbers in the table, the number is not evenly divisible, and therefore it is prime.
https://www.cprogramming.com/tutorial/modulus.html
Welcome to StackOverflow :)

Why is Wrong answer Uva : Factovisors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
For the problem 10139 - Factovisors on UVa Online Judge, 2 numbers n and m are given, and we need to check whether m divides n!.
I use the algorithm:
Generate primes till const number
Take m and get its primes factor
For each prime in m's factors, calculate getpower function for n and compare them
I test different cases it give me also Wrong Answer, any suggestion?
Here's my code:
bool Factovisor (int n, int m) {
/* Special Cases */
if(n==0 && m!=1 )
return false;
else if(n==0&&m==1)
return true;
else if(m==0)
return false;
else if(m==n||m==1)
return true;
else if (n >= m)
return true;
else {
vector <factores> factores_in_m;
int index = 0;
int k=m;
/* first I generate all primes in primes vector */
for (int i = 0; i < primes.size(); i++) {
if (primes[i] > k) {
break;
} else {
/* factores is struct contain the prime and count*/
factores f = {primes[i], 0};
while (k % primes[i] == 0) {
f.count += 1;
k = k / primes[i];
}
if (f.count) {
factores_in_m.push_back(f);
}
}
}
if (k > 1) {
if (n < k) {
return false;
} else {
factores f;
f.prime= k;
f.count =1;
factores_in_m.push_back(f);
}
}
for (int i = 0; i < factores_in_m.size(); i++) {
if (factores_in_m[i].count - get_powers(n, factores_in_m[i].prime) > 0) {
return false;
}
}
return true;
}
}
int get_powers (int n, int p) {
int result = 0, power = p;
while (power <= n) {
result += n / power;
power =power* p;
}
return result;
}
bool isPrime (int n) {
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
void get_prime () {
for (int i = 2; i < maxn0; i++) {
if (isPrime(i)) {
primes.push_back(i);
}
}
}
Maybe your prime generation is faulty, but certainly your get_powers implementation is susceptible to int overflow.
int get_powers (int n, int p) {
int result = 0, power = p;
while (power <= n) {
result += n / power;
power =power* p;
}
return result;
}
If int is, as it usually is, a 32-bit wide type, for primes larger than 46341 the computation power = power * p; overflows the first time it is done. That can lead to wrong results, for example
get_powers(10000000, 131071)
returns 52 if the overflow behaviour is wraparound modulo 232, but the correct result would be 76. Now, since m is smaller than 231, this particular one wouldn't hurt, since m cannot be divisible by 131071². But under the wraparound behaviour,
get_powers(1000000, 699733) = -2192
is negative, so for n = 1000000 and m = 2*699733 for example, you would wrongly conclude that n! isn't divisible by m.
To avoid the possible overflow, only divide by p,
int get_powers(int n, int p) {
int result = 0;
n /= p;
do {
result += n;
n /= p;
}while(n > 0);
return result;
}
From the comments:
I edited to add my functions to get primes till constant number "maxn0" – userG 2 hours ago
What value have you chosen for maxn0? – Daniel Fischer 2 hours ago
maxn0 = 10000
That value is too small.
With the primes to 10000, you are only guaranteed to correctly factorise numbers not exceeding 108 (well, since the next prime is 10007, numbers smaller than 10007² = 100140049), but the limit is given as 231, which is much larger.
Whenever a number m is given with two (not necessarily distinct) prime factors larger than 10000, you will not correctly factorise that, and that will usually lead to a wrong answer.
You need all primes &leq; √(231-1), that is all primes < 46340 to obtain the correct factorisation of all admissible m.
EDIT: wrong answer due to a misanderstanding of the question.
9 divides 7! but your algorithm will answer false because get_powers(7, 3) == 0 and 3 is a factor of 9.
It is not your implementation that is wrong but your algorithm.

c++ automatically determien prime numbers

I'm trying to figure out in c++ how to find all the prime numbers in a range (using 100 for now)
I'm not to concerned about performance, I'm starting out in c++ and trying to understand this program exercise from my book. I have my program I'm trying to use below but it keeps returning false. Any ideas? I've read through almost all of googles/bing's help as well as stack overflow. I can write code for it to work with inputting the number; just not looping through all numbers
any ideas on what i'm doing wrong?
#include <iostream>
using namespace std;
bool isPrime(long n);
int main()
{
int i;
//some vars
char emptyVar;
//first loop (to increment the number)
for (i = 0; i <= 100; i++)
{
//checking all numbers below 100
if (isPrime(i) == true)
{
//is true
cout << i << ", ";
}
else if (isPrime(i) == false)
{
//is false
cout <<"false , ";
}
}
cin >> emptyVar;
}
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}
}
}
The function isPrime does not have a return statement for every possible path of execution. For example, what does isPrime do, when n == 2?
Here's how a for loop works (in pseudo code). The general syntax is
for (initialiazion; condition; increment) {
body;
}
rest;
This can be translated into a while-loop:
initialiazion;
while (condition) {
body;
increment;
}
rest;
Especially, the condition is checked right after the intialization, before body is executed.
I suspect, you think that a for loop works like this:
initialiazion;
do {
body;
increment;
} while (condition);
rest;
i.e. the condition is checked after the first increment. But it doesn't.
It should return true if it's not a factor of EVERY i, not just the first one it encounters.
bool isPrime(long n)
{
long i =0;
//checks to see if the number is a prime
for (i = 2; i < n ; i++) // sqrt is the highest possible factor
{
if ( n % i == 0) // when dividing numbers there is no remainder if the numbers are both factors
{
// is a factor and not prime
return false;
}
}
return true;
}
Also in your case you doesn't make sense to search beyond i > n/2.
Of course you should give a look to the literature, the are really robust primality test algorithms.
Your isPrime function is incorrect. It should check all numbers and only then return true;
And this block wouldn't be ever called on your inputs:
else if (n % i != 0 && i >= 100)
{
//is not a factor
return true;
}

Slight change to bool prime function

A while ago I got an answer to a question on how to code a bool function to check if a number is prime: bool function for prime numbers.
So from this, code that works is
bool prime(int x)
{
if (x < 2) return false;
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) == 0) return false;
}
return true;
}
However if I change the code to
bool prime(int x)
{
if (x < 2) return false;
for(int i=2; i<= sqrt(x); i++) {
if ((x%i) != 0) return true;
}
return false;
}
It doesn't correctly determine whether a number is prime for many integers. I would of thought that these two segments of code would be equivalent. Is there any way of making this bool prime function work with != ?
Thanks.
No. When testing if a number is prime, you know that it is not as soon as you find a single factor.
That's why you can break out of the for loop early and return false in your first example:
if ((x%i) == 0) return false;
Finding that any single number is not a factor does not prove a number to be prime or non-prime, so you cannot terminate early under that condition.
No, it's not possible.
This original code takes advance of the ability to return early if it finds a factor. The modified version returns early the moment it finds a factor. Since you have to test all possible factors (at least, those less than the square root) before being sure that the number is not prime, the method you propose cannot be made to work.
On a side note, a small change can nearly double the efficiency of the algorithm. Since we don't have to test any even numbers larger than 2, we can test 2 first, then start the loop with 3 and increment by 2s:
bool prime(int x)
{
if (x < 2) return false;
if (x%2 == 0) return x == 2;
for(int i=3; i<= sqrt(x); i+=2) {
if ((x%i) == 0) return false;
}
return true;
}