Sorry if the question seems really trivial but I'm just learning how to code and this one kept me in front of the computer for about 2 hours without getting to realize why this happens.
I'll pass the code below.
So, in order to keep it straightforward:
isPrime() is a function that just checks if a current number is Prime or not.
nPrime() is a function that returns the n-ism prime number, given N as the parameter.
The key point here is the main function and, more precisely, the number value in the first while-loop.
If you run this code, when it reaches the last prime number by which number is divisible, it'll enter an infinite loop. This can be easily solved if you just change the first while condition from while(number > 0) to while(number > 1).
That's the weird thing I can't come to realize:
If the inner second while-loop won't exit as long as number % nPrime(index) != 0 and the last instruction of the outter first while-loop is number /= nPrime(index);, how come the program enters an infinite loop?
That last instruction set number's value to 0, so the first while-loop condition should return false and exit the loop.
What am I missing?
Thank you all for your time and patience.
PS: I got downvoted and I don't know why, so I'll make an clarification:
I've done the research. As far as I know, every source seems to agree on the same point:
the > condition returns true if and only if left operand is greater than right operand.
Which takes me to the previously written question: if number is equal to 0, how's the while-loop not evaluating the number > 0 as false and exiting from the iteration?
#include <iostream>
using namespace std;
bool isPrime(int);
int nPrime(int);
int main() {
int number = 264;
if (number > 0)
{
int index = 1;
while(number > 0)
{
while (number % nPrime(index) != 0)
{
index++;
}
cout << nPrime(index) << endl;
number /= nPrime(index);
}
}
else
cout << "Error";
return 0;
}
bool isPrime(int n)
{
bool isPrime = false;
int totalDividends = 0;
for (int i = 1; i <= n; ++i)
{
if (n % i == 0)
totalDividends++;
}
if(totalDividends == 2)
isPrime = true;
return isPrime;
}
int nPrime(int n)
{
int result = 0;
for (int i = 0; i < n; ++i)
{
do
{
result++;
} while (!isPrime(result));
}
return result;
}
What am I missing?
That last instruction set number's value to 0
No it doesn't, it never gets that far. When number equals one then number % nPrime(index) != 0 is always true, so the inner while loop never exits.
Your understanding of while loops is perfect, it's your understanding of what your own code does that is in error. This is normal for bugs like this.
Related
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;
}
I was coding to find the prime number and extract the result as a boolean (true/false or 1/0) using the below code.
#include <iostream>
using namespace std;
bool isPrimeNumber(int n) {
int m, i;
m = n / 2;
for (i = 2; i < m; i++) {
if (n % i == 0) {
return true;
} else {
return false;
}
}
}
int main() {
cout << isPrimeNumber(33);
return 0;
}
(Here the result should be 0 since 67 is a prime number)
(I'm skipping negative numbers and 0,1, but I will add it later)
Then on line 9, it said "error: control reaches end of non-void function."
I tried to find the solution on the Internet, and of course, StackOverflow. But my code was still right and buildable.
I think it has something to do with treating warnings as errors (I changed it under recommendation as a beginner). But I don't wanna change it back since I'm still learning.
Do you have a way to solve this problem without changing my setup back to normal?
When n is odd you get the error :
error: control reaches end of non-void function.
You're checking divisibility of n by only one value i=2. You have to check for each value of i from 2 to m.
Return false after iteration of for loop is completed.
Change your isPrimeNumber() function as below:-
bool isPrimeNumber(int n){
int m,i;
m = n/2;
for (i=2;i<m;i++){
if (n % i == 0){
return true;
}
}
return false;
}
This is my code for finding prime numbers between two integers. It compiles alright but giving a runtime error SIGXFSZ on codechef.
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n,m;
int t;
cin>>t;
while(t--)
{
cin>>m>>n;
for(long long j=m;j<=n;j++)
for(long long i=2;i<=sqrt(j);i++)
if(j%i==0)
break;
else cout<<j<<"\n";
cout<<"\n";
}
return 0;
}
Seems that you are wrong on logic.
According to my understanding, you are supposed to print the prime numbers between two numbers.
But your code has logical errors.
1) Code doesn't consider 2 and 3 as prime numbers.
Say, m = 1, n = 10. For j = 2, 3, the inner loop won't execute even for the single time. Hence, the output won't be shown to be user.
2) else cout<<j<<"\n"; statement is placed incorrectly as it will lead to prime numbers getting printed multiple times and some composite numbers also.
Example:
For j = 11, this code will print 11 twice (for i = 2, 3).
For j = 15, this code will print 15 once (for i = 2) though it is a composite number.
You've underexplained your problem and underwritten your code. Your program takes two separate inputs: first, the number of trials to perform; second, two numbers indicating the start and stop of an individual trial.
Your code logic is incorrect and incomplete. If you were to use braces consistently, this might be clear. The innermost loop needs to fail on non- prime but only it's failure to break signals a prime, so there can't be one unless the loop completes. The location where you declare a prime is incorrect. To properly deal with this situation requires some sort of flag variable or other fix to emulate labelled loops:
int main() {
int trials;
cin >> trials;
while (trials--)
{
long long start, stop;
cin >> start >> stop;
for (long long number = start; number <= stop; number++)
{
if (number < 2 || (number % 2 == 0 && number != 2))
{
continue;
}
bool prime = true;
for (long long odd = 3; odd * odd <= number; odd += 2)
{
if (number % odd == 0)
{
prime = false;
break;
}
}
if (prime)
{
cout << number << "\n";
}
}
}
return 0;
}
The code takes the approach that it's simplest to deal with even numbers and two as a special case and focus on looping over the odd numbers.
This is basically "exceeded file size", which means that the output file is having size larger than the allowed size.
Please do check the output file size of your program.
I am writing some function which basically takes in input a range and a 1D vector. It looks at each number in the range of values given of the vector such that:
1) If the number to the left of it is 0 they swap positions.
2) If the number to the left of it is equal to it they add.
Now up till now this was good. The issue arises when I am trying to add return statements:
1) It should return True after all iterations are complete and at least one of the if conditions is entered in each iteration.
2) It should return false after all iterations are complete and none of the conditions are entered.
Now if I put these return statements in the loops they would terminate this function here but this is not desirable since it needs to go through all the iterations first. Is the current code comparable with this or do I need to redo it in a different manner ( if not where could the return statements go?)
bool proc_num(std::vector<int>&v, int LB, int UB) {
bool check = false;
for( int i=LB+2 ; i<UB; i++) {
for(int j = i-1; j>LB; j--) {
if(v[j] == 0){
v[j] = v[i];
check = true;
} else if(v[j] == v[i]) {
v[j]= v[j]+v[i];
v[i] = 0;
check = true;
}
}
}
return check;
}
You can simply add a boolean to make sure that at least one of the if conditions are entered.
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;
}