Prime numbers c++ - c++

I have this code:
#include <iostream>
#include <cmath>
using namespace std;
int n, liczba;
int main()
{
cin >> n;
for (int i = 0; i < n; i++) {
cin >> liczba;
if (liczba < 2) {
cout << "NIE" << endl;
} else if (liczba == 2) {
cout << "TAK" << endl;
}
for (int i = 2; i < liczba; i++) {
if (liczba % i == 0) {
cout << "NIE" << endl;
break;
} else if (liczba % i != 0) {
cout << "TAK" << endl;
break;
}
}
}
return 0;
}
This program is supposed to write yes "TAK" or no "NIE" whether the number you input is prime or isn't. Variable n is the number of numbers you want to input into program, and liczba is the number you want to check if it's prime or not. It seems to work fine expect one significant thing. If I input number 9 it says yes "TAK" instead of no "NIE".. I discovered that this happens to numbers: 9,27,45,63,81 and so on.. if I add 18 starting from 9 it will happen every time.
What's wrong with my code?

You're breaking on BOTH sides of your if() test. Effectly you'll only ever test one divisor:
e.g. liczba = 9
1. if (liczba % 2 == 0) -> if (9 % 2 == 0) -> if (1 == 0) -> false
2. ...jump to else
3. if (liczba % 2 != 0) -> if (9 % 2 != 0) -> if (1 != 0) -> TRUE
4. spit out 'tak' and break out of the loop
You cannot break out of the loop "early" if you get a remainder. That means the divisor you tested is NOT a factor of the number. You can only break early if you DO get a remainder of 0, which means the number's not prime - it's composite.

Hint:
All prime numbers (except 2 and 3) can be expressed in the form 6k+1
or 6k-1, where k is a positive whole number.
Therefore, This should work:
bool IsPrime( int number )
{
if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) )
return (false);
for( int k = 1; 36*k*k-12*k < number;++k)
if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) )
return (false);
return true;
}
Taken from Determining if a number is prime.

You have not used a flag and thus it says NIE after first check. Also, you are missing an else statement.
Try this instead:
#include <iostream>
#include <cmath>
using namespace std;
int n,liczba;
int main()
{
cin >> n; //
for(int i=0;i<n;i++)
{
cin>>liczba;
if (liczba < 2)
{
cout << "NIE" << endl;
}
else if (liczba == 2)
{
cout << "TAK" << endl;
}
else
{
bool isPrime = true;
for (int i=2;i<liczba;i++)
{
if (liczba % i == 0)
{
isPrime = false;
break;
}
}
if(isPrime)
cout<<"TAK";
else
cout<<"NIE";
}
}
return 0;
}
Currently, if you input 7, It will check if 7 % 2 == 0. Since it is not, it will print "NIE" and break out of the loop.

Related

how to reiterate the do-while loop when the condition is true

The part i am not able to solve is - i am checking the number digits weather they are other than 1 or 0 using the checknumber(). Now, if the digits are other than 0 or 1 then ask the user to enter the num again till the digits are 0 and 1 only. After this, convert into binary and then again check the number is greater than -1 and the number is in negative then only exit. the main function:
int main()
{
int num = 0, flag;
while (num > -1) {
do {
cout << "Enter Number: ";
cin >> num;
} while (checknumber(num, flag) == 0);
cout << "Result in Decimal = ";
cout << binaryToDecimal(num) << endl;
}
}
This is my checknumber():
int checknumber(int number, int flag)
{
while (number != 0) {
int val = number % 10;
if ((val != 1) && (val != 0)) {
flag = 0;
break;
}
else {
flag = 1;
}
return flag;
}
}
the output i am getting when entering the number other than 0 or 1:
In your checknumber function, you're never dividing number, and thus you're stuck in an infinite loop. You're also returning on the first iteration of the loop. I do not understand the usage of flag either.
A corrected checknumber would be:
int checknumber(int number)
{
while(number != 0)
{
int val = number % 10;
if((val != 1) && (val != 0))
{
return 0;
}
number /= 10;
}
return 1;
}

Code unexpectadly giving an infinite loop

Recently started learning C++ and i wrote a simple program that defines is the given number prime or not, and when the input is zero, it finishes. But i accidentally noticed that it creates an infinite loop when the input is somewhere between 2100000000 and 2200000000. I don't know why this happens, can you please explain to me?
#include <iostream>
using namespace std;
int number, i, k;
int main()
{
do
{
cin >> number;
if (number == 0)
break;
for (i = 2; i < round(sqrt(number)) + 1; i++)
if (number % i == 0)
k++;
if ((number == 1) || (k > 0))
cout << "This number is not prime\n";
else
cout << "This number is prime\n";
k = 0;
i = 0;
} while (!(number == 0));
}
The value overflows its type (int) which maximum value is 2147483647 and it results in Undefined Behaviour. If you need to accept large numbers as input you may have to use a long long. Additionally, why check if number equals 0 twice?
#include <iostream>
#include <math.h>
int main()
{
while(true)
{
long long number;
bool isPrime = true;
std::cin >> number;
if(number == 0)
break;
for (int i = 2; i < round(sqrt(number)) + 1; i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
std::cout << "This number is prime\n"; //<== print this is this case
else
std::cout << "This number is not prime\n";
}
return 0;
}

How to check if number has a repeating digit using recursion?

I need to know if a number has a repeating digit using recursion and return 'yes' or 'no'. I am not allowed to use loops or arrays. This is what I've done untill now with 10 global variables and it works, but I think there is a better way.
#include <iostream>
using namespace std;
int counter0 = 0;
int counter1 = 0;
int counter2 = 0;
int counter3 = 0;
int counter4 = 0;
int counter5 = 0;
int counter6 = 0;
int counter7 = 0;
int counter8 = 0;
int counter9 = 0;
bool check(int k) {
int p = k % 10;;
if (k < 10) {
return false;
} else {
if (p == 0) {
counter0++;
} else if (p == 1) {
counter1++;
} else if (p == 2) {
counter2++;
} else if (p == 3) {
counter3++;
} else if (p == 4) {
counter4++;
} else if (p == 5) {
counter5++;
} else if (p == 6) {
counter6++;
} else if (p == 7) {
counter7++;
} else if (p == 8) {
counter8++;
} else if (p == 9) {
counter9++;
}
if(counter1>1 || counter2>1 || counter3>1 || counter4>1 || counter5>1 || counter6>1 || counter7>1 || counter8>1 || counter9>1)
{
return true;
}
k=k/10;
check(k);
}
}
int main() {
//cout << "Hello, World!" << std::endl;
int n;
cin >> n;
cout << (check(n) ? "yes" : "no") << endl;
//cout << n/10;
return 0;
}
#include <iostream>
using namespace std;
bool hasRepeatingDigit(int n, int mask)
{
// base case: if we have checked all the digits and didn't find any duplicates, return false
if (n == 0)
return false;
/*
p is the place of the last digit in n (n%10).
A digit can range from 0 to 9.
The place of 0 will be 1 << 0 which is 1.
The place of 1 will be 1 << 1 which is 2.
The place of 2 will be 1 << 2 which is 4.
...
...
The place of 9 will be 1 << 9 which is 512.
*/
int p = 1 << (n % 10);
// if place of p has already been marked then it's a duplicate
if (mask&p)
return true;
// otherwise scrap the last digit (n/10), mark place p and recurse on the remaining digits
return hasRepeatingDigit(n / 10, mask|p);
}
int main()
{
int n;
cin >> n;
cout << hasRepeatingDigit(n, 0) << endl;
}
Recursion problems always have a base case and an recursive case.
The base case is simple: k<11 has no repeated digits.
For the recursive case, k has repeated digits if either:
the lower two digits of k are equal, or
k/10 has repeated digits.
So:
bool check(int k) {
if (k < 11)
return false;
int digit = k % 10;
int next = k / 10;
int digit2 = next % 10;
if (digit == digit2)
return true;
else
return check(next);
// Or in one expression:
// return (digit == digit2) || check(next);
}
first, the code is incorrect...
if you enter n=11 it says 'no' but 1 repeated twice. you can fix it by changing the if statement from if(k < 10) to if(k == 0)
you can get down to the bits level but I can't see how much is useful...
in conclusion, this is the best you can do without arrays...
BUT: if you need to find if a digit repeated twice or more in a row the other answer is perfect

Count of prime numbers in random sequence (C++)

I have a task to find the count of all prime numbers in random generated sequence.
The input is:
25 10
where 25 is the number s which should be < 10^3 and is used for srand(s) and the number 10 is N(the length of the sequence) which should be < 10^9. The numbers in the sequence are generated with rand()%1000. There are no more than 100 total examples. So here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
bool isPrime(int n)
{
if (n == 0 || n == 1) return false;
for (int i = 2; i < n; i++)
{
if (n % i == 0) return false;
}
return true;
}
void Solve(int s, int N)
{
if (s >= 1000 || s <= 0 || N > 1000000000 || N <= 0)
{
cout << "s or N out of bounds!" << endl;
return;
}
int number,
count = 0,
i;
srand(s);
for (i = 1; i <= N; i++)
{
number = rand() % 1000;
if (isPrime(number))
{
count++;
}
}
cout << count << endl;
}
int main()
{
int s, N;
int counter = 0;
while (cin >> s >> N)
{
if (++counter == 100)
{
cout << "You have reached the maximum examples(100)!" << endl;
break;
}
Solve(s, N);
}
return 0;
}
And when I input 25 10 the answer should be 3 but I got 1. Where is my problem? Any help will be appreciated.

Project Euler 10 exercise

What is the sum of all the primes below 2000000?
Example of sum below 10 is 2+3+5+7 = 17
I wrote this code, but still getting the wrong answers:
I tested for numbers lower than a few hundreds, and it has shown the correct answers.
#include <iostream>
#include <math.h>
using namespace std;
bool isPrime(long n)
{
if (n < 2)
return false;
if (n == 2)
return true;
if (n == 3)
return true;
int k = 3;
int z = (int)(sqrt(n) + 1); // square root the n, because one of the product must be lower than 6, if squared root of 36
if (n % 2 == 0)
return false;
while (n % k != 0)
{
k += 2;
if (k >= z)
return true;
}
return false;
}
long primeSumBelow(long x)
{
long long total = 0;
for (int i = 0; i < x; i++) // looping for times of prime appearing
{
if (isPrime(i) == true)
total += i;
if (isPrime(i) == false)
total += 0;
}
cout << "fd" << endl;
return total;
}
int main()
{
cout << primeSumBelow(20) << endl;
cout << primeSumBelow(2000000) << endl;
system("pause");
return 0;
}
The total counter's type is correctly long long. Unfortunately the function primeSumBelow returns only long so, depending on the platform, the correctly calculated result is truncated when it's returned from this function.