How to find the nearest prime number? - c++

The goal of this method is to find the nearest prime number less than the value passed. Any value less than 3 is undefined behavior so I just return -1. The issue lies when I pass in values 5, 20, 100, and 1, this is the output:
Passed in 5 Expected 3: 5
Passed in 20 Expected 19: 19
Passed in 100 Expected 97: 97
Passed in 1 Expected -1: -1
Here is the method:
int Hash::nearestPrime(int num){
if(num <= 3){
return -1;
}
for(int i = 2; i < num; i++){
if(num == 3){
return 3;
}
if(num % i == 0 && num != i){
num--;
i = 2;
}
}
return num;
}

You could loop and decrement until the next one is found, by having a function determine if a value is prime.
#include <iostream>
int prime (int n)
{
int i;
for (i = 2; i < n; i++)
if (n % i == 0) return 0;
return 1;
}
int run (unsigned int n)
{
while (!prime (--n));
return n;
}
int main ()
{
std::cout << run (3);
return 0;
}

Your method is right but with simple mistake.
Assign i = 1 instead of i = 2 inside the if condition. Because if you assign 2 then for i++ next checking value will start from 3. But you need to check it from 2.
int Hash::nearestPrime(int num){
if(num <= 3){
return -1;
}
for(int i = 2; i < num; i++){
if(num == 3){
return 3;
}
if(num % i == 0 && num != i){
num--;
// mistake in this line
i = 1;
}
}
return num;
}

Related

previous greatest palindrome numbers before a given palindrome number

The Question is:
You are given a number 'N' in the form of a string 'S', which is a palindrome. You need to find the greatest number strictly less than 'N' which is also a palindrome.
I tried to solve this question but is giving wrong answer for some test cases. can anyone help me to correct my code.
Below is my code:
string nextSmallerPalindrome(string &s)
{
int n = s.length();
string ans = "";
if(n == 1)
{
s[0]--;
return s;
}
if(s == "11")
{
return "9";
}
// For Handling odd cases
if(n % 2 != 0)
{
int idx = n / 2;
int diff = 0;
if(s[idx] == '0')
{
s[idx] = '9';
diff = 1;
}
else
{
s[idx]--;
}
idx--;
while(idx >= 0 && diff == 1)
{
if(s[idx] == '0')
{
s[idx] = '9';
idx--;
}
else
{
s[idx]--;
diff = 0;
break;
}
}
int i = 0;
while(i < n && s[i] == '0')
{
i++;
}
for(; i < n; i++)
{
ans = ans + s[i];
}
int new_n = ans.length();
int j = 0;
int k = new_n - 1;
while(j < k)
{
if(ans[j] == ans[k])
{
j++;
k--;
}
else
{
ans[k] = ans[j];
j++;
k--;
}
}
return ans;
}
else // For handling even cases
{
int idx = n / 2 - 1;
int diff = 0;
if(s[idx] == '0')
{
s[idx] = '9';
diff = 1;
}
else
{
s[idx]--;
}
idx--;
while(idx >= 0 && diff == 1)
{
if(s[idx] == '0')
{
s[idx] = '9';
idx--;
}
else
{
s[idx]--;
diff = 0;
break;
}
}
int i = 0;
while(i < n && s[i] == '0') // For ignoring Zeros from front of the string
{
i++;
}
for(; i < n; i++) //storing all the string s in new string ans after ignoring front 0
{
ans = ans + s[i];
}
int new_n = ans.length();
int j = 0;
int k = new_n - 1;
while(j < k) // checking and changing the last half into first half
{
if(ans[j] == ans[k])
{
j++;
k--;
}
else
{
ans[k] = ans[j];
j++;
k--;
}
}
return ans;
}
}
Input Format:
The first line of the input contains an integer T denoting the number of test cases.
The first and the only line of each test case contains a string 'S', denoting the number whose next smaller palindrome is to be found.
Test Case:
19
7
77
101
1001
1221
144441
3444444443
57855875
10000001
11
1
111
101
1001
11011
1110111
1190911
20002
10011001
Excuse me, but I will not fix the code. I will rather describe how I would solve it. If you like the idea, then you will have a very easy time doing it.
A palindrome has n digits. n may be pair or odd. The first n / 2 digits (rounded upwards) is a number. Get that number (cut down the digits in the second half) and subtract 1.
Look at the result and the number of its digits. If subtracting 1 decreases the number of digits of your half-number, then handle that accordingly. Should be easy if you have the right idea.
Seems like using the same expression for idx in even cases as odd cases works better.
(It still doesn't handle the case for 7, though.)
Change this:
else // For handling even cases
{
int idx = n / 2 - 1;
to this:
else // For handling even cases
{
int idx = n / 2;
Results:
here's a working code
#include <bits/stdc++.h>
string nextSmallerPalindrome(string &s) {
// Write your code here.
string ans = s ;
if(s=="11"){
return "9";
}
int c = 0 ;
if(s.size()%2==1){
int k = s.size()/2 ;
//string ans = s ;
while(k>=0){
if(k==0 && ans[k]=='1' && ans.size()>1){
// cout<<"hola\n";
ans = ans.substr(1,ans.size()-2);
ans=ans+'9';
break;
}
if(ans[k]-'0'!=0){
int temp = ans[k]-'0';
temp-= 1 ;
ans[k] = (temp) +'0';
ans[s.size()-1-k] = (temp) +'0';
return ans;
}
else{
ans[k] = (9) +'0';
ans[s.size()-1-k] = (9) +'0';
k--;
}
}
}
else{
int k = s.size()/2 ;
while(k>=0){
if(k==0 && ans[k]=='1' && ans.size()>1){
ans = ans.substr(1,ans.size()-2);
ans=ans+'9';
break;
}
if(ans[k]-'0'!=0){
int temp = ans[k]-'0';
temp-= 1 ;
ans[k] = (temp) +'0';
ans[s.size()-1-k] = (temp) +'0';
return ans ;
}
else{
ans[k] = (9) +'0';
ans[s.size()-1-k] = (9) +'0';
if(c==0){
c++;
k-=2;
}
else k--;
}
}
}
return ans ;
}

Floating point exception: 8 on Smith number check

So I have written a code to check if a long int number is Smith, but I keep getting Floating point exception: 8, no matter what size do I fix my variables in. Not quite sure what I am missing.
#include <iostream>
bool isPrime(long int k) {
if (k == 1) return false;
for (long int i = 2; i*i < k; i++)
if (k % i == 0)
return false;
return true;
}
int main(){
long int n;
std::cin >> n;
long int sumPr = 0, sumCif = 0;
while (n > 0) {
sumCif += n % 10;
n = n/10;
}
for (long int i = 0; i*i<=n/2; i++) {
if (isPrime(i)) {
while (n % i == 0){
long int p = i;
while (p > 0) {
sumPr += (p % 10);
p = p/10;
}
n = n/i;
}
}
}
if (sumPr == sumCif) std::cout << "1" ; else std::cout << "0";
return 0;
}
The limits of this loop appear to be flawed:
for (long int i = 0; i*i<=n/2; i++) {
Possibly partly due to copy and paste from isPrime(). But the larger problem is you need to modularize this code so that you can properly test each component. And reuse modules (e.g. you implement sum of digits of a number twice in your code.) Code duplication is a potential source of error.
#include <iostream>
bool isPrime(long number) {
if (number < 2) {
return false;
}
if (number % 2 == 0) {
return (number == 2);
}
for (long divisor = 3; divisor * divisor <= number; divisor += 2) {
if (number % divisor == 0) {
return false;
}
}
return true;
}
long sum_digits(long number) {
long sum = 0;
while (number > 0) {
sum += number % 10;
number /= 10;
}
return sum;
}
long sum_prime_factor_digits(long number) {
long sum = 0;
for (long divisor = 2; divisor <= number; divisor++) {
if (isPrime(divisor)) {
while (number % divisor == 0) {
sum += sum_digits(divisor);
number /= divisor;
}
}
}
return sum;
}
bool is_smith(long number) {
if (isPrime(number)) {
return false; // only composites can play this game
}
return sum_digits(number) == sum_prime_factor_digits(number);
}
int main() {
long number;
std::cin >> number;
if (is_smith(number)) {
std::cout << "1";
} else {
std::cout << "0";
}
std::cout << "\n";
return 0;
}
TESTS
> ./a.out
4
1
> ./a.out
5
0
> ./a.out
6
0
> ./a.out
22
1
> ./a.out
4937775
1
> ./a.out
15966114
1
>
Writing clean code isn't something you do after the fact, it's what you do to help you in the debugging process.

Check whether all the pairs in an array are divisible by k

Given an array of integers and a number k, write a function that returns true if given array can be divided into pairs such that sum of every pair is divisible by k.
This code is producing correct results for all test cases except one I cannot find the glitch in it.
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int k;
cin >> k;
int flag[n] = {0};
int p = 0;
int q = 0;
if (n % 2 != 0) {
cout << "False" << endl;
} else {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if ((arr[i] + arr[j]) % k == 0 && flag[j] == 0) {
p = 1;
flag[j] = 1;
}
}
if (p == 0) {
q = 1;
cout << "False" << endl;
break;
}
}
if (q == 0) {
cout << "True" << endl;
}
}
}
return 0;
}
One of the big sources of bugs in code is messy code. So how do we clean up code? We modularize it. This means breaking up the code so that each portion of the code does one job well. Let's see what that looks like.
Function to check if something is divisible by k:
bool isDivisible(int number, int divisor) {
return number % divisor == 0;
}
Function to check all pairs:
The logic is as follows:
Take the first number in the list; call in n0.
For every remaining number n1, check if that plus the first number is divisible by k
When we find n1 such that n0 + n1 is divisible by k,
a. If the remaining numbers left over can also be split into divisible pairs, return true
b. Otherwise, continue searching
4.If we've searched through all the numbers, return false.
bool pairsDivisible(int* nums, int count, int k) {
if(count == 0) return true;
if(count % 2 != 0) return false; // count must be even
// 1.
int n0 = nums[0];
// 2.
for(int i = 1; i < count; i++) {
int n1 = nums[i];
// 3.
if(isDivisible(n0 + n1, k)) {
// Move the ith number so it's now nums[1]
std::swap(nums[1], nums[i]);
if(pairsDivisible(nums + 2, count - 2, k)) {
return true; // 3.a
} else {
// Reset the array
std::swap(nums[1], nums[i]);
}
}
}
return false;
}

Checking if a number is a Simber

A simber is defined as a positive integer in which any odd digit, if present, occurs an odd number of times, 1414414 is a simber. 4 is even and it appears four time and 1 is odd and it appears 3 times.
Here are my variables:
int is_simber(int n)
{
int numberOfTimes = 0, length = 1, x = n;
bool answer;
vector <int> nmbrs = vector <int>();
//get how many digits are in the integer
do
{
x /= 10;
length++;
}
while(x != 0)
//get the digits in the integer
for(int i = 0; i<length; i++)
{
nmbrs.push_back(((n/10^i) % 10);
}
//checking how many times a digit occurs and also testing to see if the digits
//meet the requirements
for(int i = 0; i<length; i++)
{
for(int j = 0; j<length; j++)
{
if (nmbrs.at(i) == nmbrs.at(j))
{
numberOfTimes++;
}
}
if (nmbrs.at(i) % 2 == 0 && numberOfTimes % 2 == 0)
{
answer = true;
}
else if(nmbrs.at(i) % 2 == 1 && numberOfTimes % 2 == 1)
{
answer = true;
}
else if(nmbrs.at(i) % 2 == 0 && numberOfTimes % 2 == 1)
{
answer = false;
break;
}
else if(nmbrs.at(i) % 2 == 1 && numberOfTimes % 2 == 0)
{
answer = false;
break;
}
}
return answer;
}
Your code has compilation errors.
^ is Binary XOR Operator. You can't expect it to produce pow(10,i). So replace nmbrs.push_back(((n/10^i) % 10); with nmbrs.push_back(((n/pow(10,i)) % 10);
When I was able to remove the compilation errors, i realized your code has logical errors too. As your given definition of simber, int is_simber(int n) should be fair and simple.
bool is_simber( int n )
{
if ( n<0 ) return false; // simber is a positive integer
int digitCount[10] = {}; // initializing all with 0;
// digitCount array holds the number of occurance of a digit
// so d[1] holds the number of times 1 occurred
// d[2] holds the number of times 2 occurred and so on ...
while( n ){
int d = n%10;
n /= 10;
digitCount[d]++;
}
// we just have to check
// any odd digit, if present, occurs an odd number of times
for( int i=1; i<=9; i= i+2) // Attention i=i+2, to iterate over just odd numbers
{
if( digitCount[i] != 0 && digitCount[i]%2 == 0 ) return false;
}
return true;
}
My definition of is_simber
inline bool is_even(int n) { return n % 2 == 0; }
bool is_simber(int n) {
if (n < 0) return false;
int digits[10] = {0};
for (; n; n /= 10) ++digits[n % 10];
for (int i = 0; i < 10; i += 2)
if (!is_even(digits[i]) && is_even(digits[i + 1])) return false;
return true;
}
LIVE DEMO

sieve of Eratosthenes C++ algorithm

I am trying to implement this algorithm and I have having a hard time working out the algorithm to work for finding the prime numbers up to 1000. I don't really understand but my code is not giving me the correct output, if you can suggest a way I should change my code I would greatly appreciate it.
#include <iostream>
using namespace std;
bool isPrime(int n);
int main() {
int i;
for(i = 1; i <= 1000; i++){
if( isPrime(i)) cout << "This number " << i << " is a prime. " << endl;
}
}
bool isPrime(int n){
if(n <= 1){
return false;
}
if(n == 2){
return true;
}
for(int i = 2; i < n; i++){
if(n % i == 0){
return false;
}else{
return true;
}
}
}
Your decision inside the for loop inside isPrime() is wrong. This is a criterion to terminate the loop:
if(n % i == 0){
but the elsepart is no reason to terminate. You have to wait until the for loop finished. Like this:
for(int i = 2; i < n; i++){
if(n % i == 0){
// Here, we are sure that n can be divided by any other numbers than 1 and n.
return false;
}
}
// Here, we are sure that n cannot be divided by any number 2 .. (n-1).
return true;
}
By the way, you only have to check until the square root of n. You can spare the rest.
There is problem in your isPrime function
bool isPrime(int n){
if(n <= 1){
return false;
}
if(n == 2){
return true;
}
for(int i = 2; i < n; i++){
if(n % i == 0){
return false;
}
else{
return true; /* this line is very dangerous. When there is odd number it is not divisible by two so the control goes to else block and you get every odd number as your prime number */
}
}
}
Instead use this
bool isPrime(int n){
if(n <= 1){
return false;
}
if(n == 2){
return true;
}
for(int i = 2; i < n; i++){
if(n % i == 0){
return false;
}
}
return true;
}
For Sieve Of Erastosthenes
try this code it may help
int b;
cout << "Enter upper limit" << endl;
cin >> b;
bool *x;
x = new bool[b];
x[2] = true;
for (int i = 2; i < b; i++)
{
int count = 2;
if (x[i])
{
cout << i << endl;
while (i*count < b)
{
x[i*count] = false;
count++;
}
}
}
The problem is in the isPrime function.
Your isPrime function says if the the first value of i (i.e 2) is not divided by n then return true. So for eg. 21, 27 etc are also counted as a prime number.
You can use a flag variable in the isPrime function and used it to determine whether the n is prime or not. Like this
boolean prime = true;
for(int counter = 2; counter <= number / 2; counter++) {
if(number % counter == 0) {
prime = false;
break;
}
}
return prime;
I don't think this is Sieve of Eratosthenes algorithm. If you want to implement this algorithm then you can read from here.