Check Number sequence - c++

You are given S a sequence of n integers i.e. S = s1, s2, ..., sn. Compute if it is possible to split S into two parts : s1, s2, ..., si and si+1, si+2, ….., sn (0 <= i <= n) in such a way that the first part is strictly decreasing while the second is strictly increasing one.
Note : We say that x is strictly larger than y when x > y.
So, a strictly increasing sequence can be 1 4 8. However, 1 4 4 is NOT a strictly increasing sequence.
That is, in the sequence if numbers are decreasing, they can start increase at one point. And once number starts increasing, they cannot decrease at any point further.
Sequence made up of only increasing numbers or only decreasing numbers is a valid sequence. So in both the cases, print true.
You just need to print true/false. No need to split the sequence.
Input format :
Line 1 : Integer 'n'
Line 2 and Onwards : 'n' integers on 'n' lines(single integer on each line)
Output Format :
"true" or "false" (without quotes)
Constraints :
1 <= n <= 10^7
Sample Input 1 :
5
9
8
4
5
6
Sample Output 1 :
true
Sample Input 2 :
3
1
2
3
Sample Output 2 :
true
Sample Input 3 :
3
8
7
7
Sample Output 3 :
false
Explanation for Sample Format 3 :
8 7 7 is not strictly decreasing, so output is false.
Sample Input 4 :
6
8
7
6
5
8
2
Sample Output 4 :
false
Explanation for Sample Input 4 :
The series is :
8 7 6 5 8 2
It is strictly decreasing first (8 7 6 5). Then it's strictly increasing (5 8). But then it starts strictly decreasing again (8 2). Therefore, the output for this test case is 'false'
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
int p;
cin >> p;
bool isDec = true;
int i = 1,c;
while(i <= n - 1){
cin >> c;
if(c > p){
if(isDec == true){
isDec = false;
}
isDec = true;
p = c;
} else if(c < p){
if(isDec == false){
isDec = false;
}
isDec = true;
p = c;
} else {
isDec = false;
break;
}
i++;
}
if(isDec){
cout << "true" << endl;
} else{
cout << "false" << endl;
}
}
What is wrong with this code? It failed for last test case.

#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int current_term;
cin>>current_term;
bool isDecreasing = true,is_valid_sequence_yet=true;
int i=2;// first term of sequence has already been taken
while(i<=n){
int next_term;
cin>>next_term;
if(is_valid_sequence_yet && isDecreasing && current_term>next_term){
current_term=next_term;
isDecreasing=true;
}else if(is_valid_sequence_yet && current_term < next_term){
current_term=next_term;
isDecreasing = false;
}else{
is_valid_sequence_yet=false;
}
i++;
}
if(is_valid_sequence_yet){
cout << "true" << endl;
}else{
cout << "false" <<endl;
}
}

import java.util.*;
public class test{
public static void main(String args[]){
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=s.nextInt();
}
boolean flag=true;
for(int i=0;i<n-2;i++){
if((arr[i]<arr[i+1])&& arr[i+1]>arr[i+2])){
flag=false;
break;
}
}
System.out.print(flag);
}
}

int num , temp = 1 , i =1 ;
cin>>num;
bool Isdec = true;
int Previes_num , current_num;
cin>>Previes_num;
while(i <= num-1){
cin>>current_num;
if(Previes_num > current_num){
if(Isdec){
Isdec = true ;
temp++;
}
else{
cout<<"false";
return 0;
}
}
else if(current_num > Previes_num){
if(Isdec){
Isdec = false ;
}
}
else{
cout<<"false";
return 0 ;
}
++i;
Previes_num=current_num;
}
if(temp==num){
cout<<"true";
}
else if(Isdec == 0){
cout<<"true" ;
}
return 0;
}

#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << endl;
int t1,t2; // two consecutive terms
cin >> t1;
cout << endl;
bool changed=false; // this will turn true once the series has switched to increasing mode
bool result=true; // we will change it to flase if any condition is voilated
for(int i=2;i<=n;i++) { // i=2 since we already took one input
cin >> t2;
cout << endl;
if (t1>t2) {
if (changed == true) {//we are in the increasing part
result = false; //since now the terms are decreasing but we are in incresaing part the series is no longer valid
}
}
else if (t1<t2) {
if ( changed == false) {
changed = true; // the series has now changed to increasing series if it wasn't before
}
}
else {
result = false; // if tow terms are equal the result is automatically false
}
t1=t2; // replacing the terms to get new input
}
if (result) cout << "true"; // if we dont do this we get 0,1 as output
else cout << "false";
}
We need to set two bools as shown. Once our series changes from decreasing to increasing we will set change to true.
If we already have change set to true but our series changes again from decreasing to increasing we will set result bool to false.
In the end we can output result to get our required answer.
In case we get two consecutive terms equal we straightaway set result to false as it directly violates our condition of strictly increasing or strictly decreasing.
We will not use break anywhere because user is expected to give all the inputs and then result is displayed.
As for debugging your code, you need to change your approach. Also, what did you even intend to accomplish by this :
if(isDec == false){
isDec = false;
}

Related

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

I am trying to solve 12503 problem in UVA online judge. I think their is a problem while using string::back()

The problem is simple. But I tried to submit two different codes, one of them got a WA verdict while the other one got a AC verdict. The solutions are nearly same. Just by changing the input mechanism the solution gets accepted. I can't understand what the problem is. Link to the problem is here.
Abridged Problem Statement:
You have a robot standing on the origin of x axis. The robot will be given some instructions. Your
task is to predict its position after executing all the instructions.
LEFT: move one unit left (decrease p by 1, where p is the position
of the robot before moving)
RIGHT: move one unit right (increase p
by 1)
SAME AS i: perform the same action as in the i-th
instruction. It is guaranteed that i is a positive integer not
greater than the number of instructions before this
Input:
The first line contains the number of test cases T (T ≤ 100). Each test case begins with an integer n
(1 ≤ n ≤ 100), the number of instructions. Each of the following n lines contains an instruction.
Output
For each test case, print the final position of the robot.
Note that after processing each test case, the
robot should be reset to the origin.
Sample Input
2
3
LEFT
RIGHT
SAME AS 2
5
LEFT
SAME AS 1
SAME AS 2
SAME AS 1
SAME AS 4
Sample Output
1
-5
Here's the code which got AC verdict:
#include <bits/stdc++.h>
using namespace std;
int TC = 0 , N = 0 , p = 0 , in = 0;
string instruction , as;
vector<string> instructions;
int main() {
cin >> TC;
while(TC--) {
cin >> N; p = 0; scanf("\n");
instructions.assign(N , "");
for(int i = 0 ; i < N ; ++i) {
cin >> instruction;
if(instruction.compare("LEFT") == 0) {
instructions[i] = instruction;
}
else if(instruction.compare("RIGHT") == 0) {
instructions[i] = instruction;
}
else { scanf("\n");
cin >> as >> in;
instructions[i] = instructions[in - 1];
}
}
for(auto x : instructions) {
if(x.compare("RIGHT") == 0) ++p;
else --p;
}
cout << p << endl;
instructions.clear();
}
return 0;
}
Here, is the code which got WA verdict:
#include <bits/stdc++.h>
using namespace std;
int TC = 0 , N = 0 , p = 0 , in = 0;
string instruction , as;
vector<string> instructions;
int main() {
cin >> TC;
while(TC--) {
cin >> N; p = 0; scanf("\n");
instructions.assign(N , "");
for(int i = 0 ; i < N ; ++i) {
getline(cin , instruction);
if(instruction.compare("LEFT") == 0) {
instructions[i] = instruction;
}
else if(instruction.compare("RIGHT") == 0) {
instructions[i] = instruction;
}
else {
instructions[i] = instructions[instruction.back() - '0' - 1]; // I think the problem is here but don't know what it is.
}
}
for(auto x : instructions) {
if(x.compare("RIGHT") == 0) ++p;
else --p;
}
cout << p << endl;
instructions.clear();
}
return 0;
}
Maybe instruction.back() is creating some problem. Please clarify my doubt.

How to reverse a negative integer recursively in C++?

I am working on some recursion practice and I need to write a program that reverse the input of an integer
Example of input : cin >> 12345; The output should be 54321
but if that integer is negative the negative sign needs to be appended to only the first number.
Example of input : cin >> -1234; output -4321
I am having a hard time getting my program to adapt to the negative numbers. The way I have it set up if I run
Example of test : 12345 I get the right output 54321
So my recursion and base are successful. But if I run a negative I get
Example of test : -12345 I get this for a reason I don't understand -5-4-3-2 1
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true)
in = 0 - in;
cout << in % 10;
reverse(in / 10);
}
}
To reverse a negative number, you output a - and then reverse the corresponding positive number. I'd suggest using recursion rather than state, like this:
void reverse(int in)
{
if (in < 0)
{
cout << '-';
reverse(-in);
}
else
{
// code to recursively reverse non-negative numbers here
}
}
Split the reverse function into two parts: the first part just prints - (if the input is negative) and then calls the second part, which is the recursive code you have. (You don't need any of the if (negative) ... handling any more, since the first part already handled it.)
Incidentally, if (bool_variable == true) ... is overly verbose. It's easier to read code if you say something like if (value_is_negative) ....
Your recursive function doesn't hold state. When you recurse the first time, it prints the '-' symbol but every time you send back a negative number to the recursion, it runs as if it is the first time and prints '-' again.
It's better to print '-' first time you see a negative number and send the rest of the number as a positive value to the recursion.
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true) {
cout << '-';
negative = false;
}
cout << in % 10;
reverse(in / 10);
}
}
int reverse(long int x) {
long int reversedNumber = 0, remainder;
bool isNegative = false;
if (x <0){
isNegative = true;
x *= -1;
}
while(x > 0) {
remainder = x%10;
reversedNumber = reversedNumber*10 + remainder;
x= x/10;
}
if (isNegative) {
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber*(-1);
}
else
{
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber;
}
}

C++ Prime Number Program not recognizing 3? [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
My program is supposed to detect prime numbers from 1 to 100 and save them to a file.
For some reason, it does not recognize 3 but mistakenly recognizes some multiples (27, 33, etc) of 3 as prime.
Code follows...
/* This program will use a function determine if a number is prime.
When called this function will be used to determine all
prime numbers from 1- 100 and save them to a file*/
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
bool isPrime(int);// function prototype
int main()
{
ofstream fout;
fout.open("prime.txt");
bool result;
int num; // variable to hold integer number
for (num = 1; num >= 1 && num <= 100; num++)
{
result =isPrime(num);
if (result == true)
{
fout << num<< endl;
}
else
{
cout << num << " is not prime." <<endl;
}
}
fout.close();
system("pause");
return 0;
}
bool isPrime(int test)
{
//define prime as a bool integer
bool prime;
// check for 2, a prime number that will not be caught by for loop algorithm
if (test == 2)
{
prime = true;
}
// eliminate all even numbers other than 2
else if ( test%2 == 0)
{
prime = false;
}
// eliminate 0
else if ( test == 0)
{
prime = false;
}
//eliminate 1, which is not prime or composite
else if ( test == 1)
{
prime = false;
}
// if test is not yet determined, check using algorithm
// this algorithm returns the remainder of a number (test)
// divided by an integer (i) in the range of i = 1
// to i = sqrt(number)
else
{
for(int i = 1; i <= (sqrt(test));i++)
{
if (test%i == 0)
{
prime = false;
}
else if (test%i != 0)
{
prime = true;
}
}
}
if (prime == true)
{
cout << "The number " <<test << " is prime." <<endl;
}
return prime;
EDIT for code fix:
/* This program will use a function determine if a number is prime.
When called this function will be used to determine all
prime numbers from 1- 100 and save them to a file*/
#include<iostream>
#include<cmath>
#include<fstream>
using namespace std;
bool isPrime(int);// function prototype
int main()
{
ofstream fout;
fout.open("prime.txt");
bool result;
int num; // variable to hold integer number
for (num = 1; num >= 1 && num <= 100; num++)
{
result =isPrime(num);
if (result == true)
{
fout << num<< endl;
}
else
{
cout << num << " is not prime." <<endl;
}
}
fout.close();
system("pause");
return 0;
}
bool isPrime(int test)
{
//define prime as a bool integer
bool prime;
double sqrt_num = sqrt(test);
//check for number 2 which algorithm wont catch, but is prime
if (test ==2)
{
return true;
}
// check if even and return false
else if ( test% 2 == 0)
{
return false;
}
//eliminate 1, which is not prime or composite, and 0.
else if ( test == 0 || test == 1)
{
return false;
}
// if test is not yet determined, check using algorithm
// this algorithm returns the remainder of a number (test)
// divided by an integer (i) in the range of i = 1
// to i = sqrt(number)
else
{
for(int i = 3; i <= sqrt_num;i+=2)
{
if (test%i == 0)
{
return false;
}
}
}
return true;
}
The biggest error in your code is your for-loop:
for(int i = 1; i <= (sqrt(test));i++)
{
if (test%i == 0)
{
prime = false;
}
else if (test%i != 0)
{
prime = true;
}
}
If we step through if for your false test cases 3 and 27, we see that for 3 it is this:
for (int i = 1; i <= 1; i++)
{
if (3 % 1 == 0)
{
prime = false;
}
else if (3 % 1 != 0)
{
prime = true;
}
}
The loop will be computed once, and the result (false) returned. The reason for this is that your loop starts with 1 and because every number is divisible by 1, every number which is only checked for 1 will always be composite. To fix this we just start with the number 2. If we do this, we have to set an initial value for "prime" because otherwise we would return a null value. Our initial value will be true, which means every number is prime until proven otherwise which, conveniently, is exactly what our for loop does.
The second error occurs when you reach the last iteration of the loop for 27:
//i == 5
for (int i = 1; i <= 5; i++)
{
if (27 % 5 == 0)
{
prime = false;
}
else if (27 % 5 != 0)
{
prime = true;
}
}
Because the last iteration sets prime to true, true is returned, which is obviously false. A possible solution is to exit the loop if we encounter an i for which number % i == 0 holds, as this means we have found a valid factor for said number.
TL; DR: Solving the errors we got:
start with the number 2 instead of one to get rid of the corner case 3 (and 2 as well)
if a valid factor is found the number is definitely composite and we set prime to false and exit the loop because we found a result.
Using the fixes and simplifying we get:
bool isPrime(int number)
{
// special cases 0 and 1
if (i == 0 || i == 1)
{
return false;
}
// else check from i = 2 to sqrt(number) if any of them divides the number
// if yes, the number is not prime and it returns false.
for (int i = 2; i <= sqrt(number); i++)
{
if (number % i == 0)
{
return false;
}
}
// if the number is not 0 or 1 and has passed the loop, it must be prime,
// hence we can return true
return true;
}
A small optimisation to make would be checking if it is even and if not just testing division by odd numbers. We would then replace the for-loop by:
if (number % 2 == 0)
{
return false;
}
for (int i = 3; i <= sqrt(number); i=i+2)
{
if (number % i == 0)
{
return false;
}
}
(int)sqrt(3) is 1, every test%1 will return 0 because division by 1 has no remainder.
You should stop the loop once you find proof that the number is not prime. If you keep it going the result will be misleading.
Note: sqrt() is an expensive function. Consider saving its result in a variable so you don't have to run it every loop.
Since you start the loop with i = 1, the condition test%i == 0 is always true.
So you should start it with i = 2, which will allow you to test numbers greater than or equal to 4.
In addition, you should break the loop once you set prime = false.
You will have to test 3 separately, since 2 > sqrt(3).
A few suggestions for improvement:
bool isPrime(int number)
{
// Handle 0 and 1
if (number < 2)
return false;
// Handle 2 and 3
if (number < 4)
return true;
// Handle numbers that are not adjacent to a multiple of 6
if (number%2==0 || number%3==0)
return false;
// Calculate once
int root = (int)sqrt(number);
// Check divisibility by numbers that are equal to -1(mod6)
for (int i=5; i<=root; i+=6)
{
if (number%i == 0)
return false;
}
// Check divisibility by numbers that are equal to +1(mod6)
for (int i=7; i<=root; i+=6)
{
if (number%i == 0)
return false;
}
return true;
}

Prime number C++ program

I am not sure whether I should ask here or programmers but I have been trying to work out why this program wont work and although I have found some bugs, it still returns "x is not a prime number", even when it is.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i < b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
break;
}
//Other wise if the user input does have a remainder and is the last of the loop, return true (it is a prime)
else if ((a % i != 0) && (i == a -1)) {
return (1);
break;
}
}
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
cout << "\n\nPress enter to exit...";
getchar();
getchar();
return 0;
}
Sorry if this is too localised (in which case could you suggest where I should ask such specific questions?)
I should add that I am VERY new to C++ (and programming in general)
This was simply intended to be a test of functions and controls.
i can never be equal to a - 1 - you're only going up to b - 1. b being a/2, that's never going to cause a match.
That means your loop ending condition that would return 1 is never true.
In the case of a prime number, you run off the end of the loop. That causes undefined behaviour, since you don't have a return statement there. Clang gave a warning, without any special flags:
example.cpp:22:1: warning: control may reach end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
If your compiler didn't warn you, you need to turn on some more warning flags. For example, adding -Wall gives a warning when using GCC:
example.cpp: In function ‘bool primetest(int)’:
example.cpp:22: warning: control reaches end of non-void function
Overall, your prime-checking loop is much more complicated than it needs to be. Assuming you only care about values of a greater than or equal to 2:
bool primetest(int a)
{
int b = sqrt(a); // only need to test up to the square root of the input
for (int i = 2; i <= b; i++)
{
if (a % i == 0)
return false;
}
// if the loop completed, a is prime
return true;
}
If you want to handle all int values, you can just add an if (a < 2) return false; at the beginning.
Your logic is incorrect. You are using this expression (i == a -1)) which can never be true as Carl said.
For example:-
If a = 11
b = a/2 = 5 (Fractional part truncated)
So you are running loop till i<5. So i can never be equal to a-1 as max value of i in this case will be 4 and value of a-1 will be 10
You can do this by just checking till square root. But below is some modification to your code to make it work.
#include <iostream>
using namespace std;
bool primetest(int a) {
int i;
//Halve the user input to find where to stop dividing to (it will remove decimal point as it is an integer)
int b = a / 2;
//Loop through, for each division to test if it has a factor (it starts at 2, as 1 will always divide)
for (i = 2; i <= b; i++) {
//If the user input has no remainder then it cannot be a prime and the loop can stop (break)
if (a % i == 0) {
return(0);
}
}
//this return invokes only when it doesn't has factor
return 1;
}
int main(void) {
int user;
cout << "Enter a number to test if it is a prime or not: ";
cin >> user;
if (primetest(user)) {
cout << user << " is a prime number.";
}
else {
cout << user<< " is not a prime number.";
}
return 0;
}
check this out:
//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;
int main()
{
int a = 2; //start from 2
long long int b = 1000; //ends at 1000
for (int i = a; i <= b; i++)
{
for (int j = 2; j <= i; j++)
{
if (!(i%j)&&(i!=j)) //Condition for not prime
{
break;
}
if (j==i) //condition for Prime Numbers
{
cout << i << endl;
}
}
}
}
main()
{
int i,j,x,box;
for (i=10;i<=99;i++)
{
box=0;
x=i/2;
for (j=2;j<=x;j++)
if (i%j==0) box++;
if (box==0) cout<<i<<" is a prime number";
else cout<<i<<" is a composite number";
cout<<"\n";
getch();
}
}
Here is the complete solution for the Finding Prime numbers till any user entered number.
#include <iostream.h>
#include <conio.h>
using namespace std;
main()
{
int num, i, countFactors;
int a;
cout << "Enter number " << endl;
cin >> a;
for (num = 1; num <= a; num++)
{
countFactors = 0;
for (i = 2; i <= num; i++)
{
//if a factor exists from 2 up to the number, count Factors
if (num % i == 0)
{
countFactors++;
}
}
//a prime number has only itself as a factor
if (countFactors == 1)
{
cout << num << ", ";
}
}
getch();
}
One way is to use a Sieving algorithm, such as the sieve of Eratosthenes. This is a very fast method that works exceptionally well.
bool isPrime(int number){
if(number == 2 || number == 3 | number == 5 || number == 7) return true;
return ((number % 2) && (number % 3) && (number % 5) && (number % 7));
}