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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.