Check if number(s) is prime in C++ - c++

I'm doing an online challenge and came across one problem! I have worked out the logic on paper, but it seems my problem doesn't work. All it does is return 0 as output.
My code so far:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int nums[50];
string res[50];
int o = 0;
for(int i=0;i<n;i++)
{
cin >> nums[i];
}
for(int i=0;i<n;i++)
{
int deliteli=1;
for(int j=1;j<=nums[i];j++)
{
if(nums[i]%j==0)
{
deliteli++;
}
}
if(deliteli == 2){
res[0] = "YES";
o++;
}
else if(deliteli != 2){
res[0] = "NO";
o++;
}
}
for(int i=0;i<o;i++)
{
cout << res[i] << endl;
}
return 0;
}
What I am doing is firstly input N number, which means how long the array is going to be and then check for each number in the array whether it's prime or not. Any ideas what am I doing wrong?

deliteli should start at 0.
deliteli should be reset at the beginning of the loop.
You use res[i] instead of res[0], otherwise you keep overwriting the first element.
j%nums[i] should be nums[i]%j, because a%b returns the remainder from dividing a by b.
' is for single characters only (C++ is perfectly happy allowing things that shouldn't be allowed to compile and run). " is for strings.
Final code:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int nums[50];
string res[50];
int o = 0;
for(int i=0;i<n;i++)
{
cin >> nums[i];
}
for(int i=0;i<n;i++)
{
int deliteli=0;
for(int j=1;j<=nums[i];j++)
{
if(nums[i]%j==0)
{
deliteli++;
}
}
if(deliteli == 2){
res[i] = "YES";
o++;
}
else if(deliteli != 2){
res[i] = "NO";
o++;
}
}
for(int i=0;i<o;i++)
{
cout << res[i] << endl;
}
return 0;
}
Test.

for(int j=1;j>=nums[i];j++)
{
...
}
It seems like you have the loop condition wrong. It should be:
for(int j=1;j<=nums[i];j++) //Change here
{
...
}

To check if nums[i] can be divided by j you are doing j%nums[i]==0, but that needs to be nums[i]%j==0.
Your deliteli counter also has a problem.
You need to reinitialize it for each number, otherwise it will just add to it.
Also you are always setting res[0], but you would want to set res[i].

first: to check if nums[i] can be divided by j you are doing j%nums[i]==0, but that needs to be nums[i]%j==0.
second:
change for(int j=1;j>=nums[i];j++)
to for(int j=1;j<=nums[i];j++)
and last: you don't have to test number nums[i] up to nums[i] but just to square root of this so change it to sqrt(nums[i])+1. It might be slight improvement to the speed of your algorithm.

Related

How can I make diagonal shapes in C++?

I currently have some problem with looping. Please help me to make some program that run like this :
But I have made some program that runs kind of like this :
And this is my code for my program. Maybe you can correct the wrong syntax.
#include <iostream>
using namespace std;
int main()
{
int input;
char abjad;
abjad='A';
cout<<"INPUT = ";
cin>>input;
for(int i=1;i<=input;i++){
for(int j=0;j<i;j++){
cout<<abjad;
abjad++;
}
cout<<i+1;
for(int k=0;k<input-i-1;k++){
cout<<abjad;
abjad++;
}
cout<<endl;
}
}
}
Here is your solution:
// ...
for (int i = 0; i < input; i++) {
for (int j = 0; j < i; j++) {
cout << abjad;
abjad++;
}
cout << i + 2;
// ...
I have only changed the first for loop to start with 0 instead of 1 and as a compensation to this the condition changed to i < input instead of <=. Also number output is now cout << i + 2;
This should fix your issue.

End a while loop that continue ask for string input until I enter -1

I have to create a menu that holds item names, I can do it with a for loop that ends until the max has been reach, but how do I do it with a while loop that will continue ask until the max is reached or I enter -1
I tried with a for loop and it worked, but I have to use a while loop that can stop when I tell it to stop.
#include <iostream>
using namespace std;
void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
int MAX_MENU_ITEMS);
int main()
{
const int MAX_MENU_ITEMS = 5;
char menu_list[MAX_MENU_ITEMS][50];
float price_list[MAX_MENU_ITEMS];
int num_menu_items;
read_in_menu(menu_list, price_list, num_menu_item, MAX_MENU_ITEMS);
}
void read_in_menu(char menu_list[][50], float price_list[], int& num_menu_items,
int MAX_MENU_ITEMS)
{
for (int i = 0; i < MAX_MENU_ITEMS; i++)
{
cout << "Enter Names: ";
cin.getline(menu_list[i], 20);
}
}
I want to use a while loop that will continue going until I input -1 or reach the maximum. I want to stop the while loop whenever I want instead of the for loop where I have to reach the max.
If I understand correctly, something like this should work:
int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS || input == "-1") {
cout << "Enter Names: ";
cin.getline(input, 20);
if(input != "-1") { //to avoid setting menu_list[i] = "-1"
menu_list[i] = input;
}
MAX_MENU_ITEMS++;
}
or using break:
int i = 0;
string input = "";
while(i < MAX_MENU_ITEMS) {
cout << "Enter Names: ";
cin.getline(input, 20);
if(input == "-1") {
break;
}
menu_list[i] = input;
MAX_MENU_ITEMS++;
}
Whenever you want to exit a loop you can use the break keyword.
for(int i = 0; i < MAX; i++){
if(i > 10){
break;
}
doWork();
}
I was able to get it with a pointer lol.
void read_in_menu(char menu_list[5][20], float price_list[], int &num_menu_items, int MAX_MENU_ITEMS){
int i = 0;
char *p = "-1";
while(i<MAX_MENU_ITEMS){
cout << "Enter Name" << endl;
cin.getline(menu_list[i],20);
if(strcmp(menu_list[i], p)){
i++;
}else{
break;
}
}
}
You can transform for loop to other loops. For example:
For
for(int i = 0; i < 10; i++)
DoSomething();
While
int i = 0;
while(i < 10){
DoSomething();
i++;
}
do-while
int i = 0;
do{
DoSomething();
i++;
}
while(i < 10);
To control the loops use continue and break keywords. Keyword continue will skip the current iteration of the loop and break will exit the loop. These are usually conditioned by if statement.

Checking Duplicates Numbers In Array c++

I wrote a simple C++ program that finds how many duplicates are in the array.
This works perfectly for me but this is very long code. And I would like to know if there is any short code which may perform this task successfully:
#include<iostream>
using namespace std;
int main()
{
int a[10];
int reper=0,word=0,flage=0,number[10]={
0
};
//Getting Input From User
for (int i = 0; i <=9; i++)
{
cout<<"Enter The Value For "<<i<<" Index"<<endl;
cin>>a[i];
}
//Checking The Duplicates Numbers
for (int i = 0; i <= 9; i++)
{
reper=0;
flage=0;
for (int j = 0; j <=9; j++)
{
if (a[i]==a[j])
{
if (i!=j)
{
reper++;
}
}
}
number[i]=a[i];
for (int k = 0; k <=9; k++)
{
if (i!=k)
{
if(number[i]==number[k])
{
flage=1;
break;
}
}
}
//If There Are Duplicates Then Prints That Numebr, How Many Times It Repeated And Total Occurance Of That Number In The Array
if (reper!=0&&flage==0)
{
cout<<"Repeated Number Of The Array Is : "<<a[i]<<" ";
cout<<"And This Number Repeated "<<reper<<" Times "<<"And Total Occurance Of This Number is : "<<reper+1<<endl;
word=a[i];
}
}
//If There Is Nothing Any Duplicate In The Array Then Simply Prints This Message On Console
if (reper==0&&word==0)
{
cout<<"There Is Nothing Any Repeated Number Of This Array: "<<endl;
}
system("Pause");
return 0;
}
IMHO the easiest way to implement this - using http://en.cppreference.com/w/cpp/container/multiset. It has logarithmic complexity and inner methods to count repeated items.
Refer an example below:
#include <iostream>
#include <set>
int main(int argc, char *argv[])
{
std::multiset<int> ms;
//Getting Input From User
for (int i = 0; i <=9; i++)
{
std::cout<<"Enter The Value For "<<i<<" Index"<<std::endl;
int val;
std::cin>>val;
ms.insert(val);
}
bool repeated_number_found=false;
std::multiset<int>::const_iterator it = ms.begin();
while (it != ms.end()) {
int reper=ms.count(*it);
if (reper > 1){
std::cout << "Number " << *it << " repeated for " << reper << " times" << std::endl;
repeated_number_found=true;
}
it = ms.upper_bound(*it);
}
if (!repeated_number_found){
std::cout<<"There Is Nothing Any Repeated Number Of This Array"<<std::endl;
}
return 0;
}
But using this container you will loose first entrance of repeated number, if it matters to you, I will recommend using struct or std::pair to hold entrance number with entered number. In this case you will need to provide custom comparator also (refer to doc.)
I think the better way to achieve this would be to sort the array and do something like this :-
(include the header file algorithm before doing this.)
vector <int> a (10,0);
for (int i = 0; i <=9; i++)
{
cout<<"Enter The Value For "<<i<<" Index"<<endl;
cin>>a[i];
}
int count = 0;
sort(a.begin(), a.end());
for(int i = 0; i < a.size() - 1; i++) {
if (a[i] == a[i + 1]) {
count++;
}
}
cout << count << endl;

display wheter or not an array entered by the user is unique or not

I am new to C++ I am making an array based off of user input and displaying whether the array is unique or not. my initial thought is I have to end up creating another array to store values and then compare the elements. My code compiles without errors but does not do what I want it to do. I can't used advanced methods such as hashmaps or vectors. Any help or insight is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myArray[6];
string name;
int i, k;
int ov = 0;
int newVal = 0;
for (int index = 0; index < 6; index++)
{
cout << "Enter number a number: ";
cin >> myArray[index];
}//end loop for
for (i = 0; i < 6; i++)
{
ov = myArray[i];
}
for (k = i + 1; k < 6; k++)
{
if (ov == myArray[k])
{
newVal = 1;
}
}
if (newVal == 1)
{
cout << "Not all unique";
}
else
{
cout << "All unique";
}
cin.get();
return 0;
}

Wrong answer calls on palindrome

I coded palindrome program.
I think this code is right especially is_palindrome procedure.
But I don't know why this answers wrong.
Because when I input 2 1 1, return must be This is palindrome.
But it answers the other.
#include <iostream>
using namespace std;
bool is_palindrome(int input[], int numOfSlots);
int main(void) {
int n;
cin >> n;
int *input = new int[n]; // A dynamic array with n slots
for (int i = 0; i < n; i++) {
cin >> input[i];
}
if (is_palindrome(input, n) == true) {
cout << "This is a palindrome.";
}
else {
cout << "This is NOT a palindrome.";
}
return 0;
}
bool is_palindrome(int input[], int numOfSlots) {
int i = 0;
while (i < numOfSlots/2)
{
if (input[i] != input[numOfSlots-i])
return false;
i++;
}
return true;
}
You are going one past then end of the array in if (input[i] != input[numOfSlots-i]). When i == 0 then input[numOfSlots-i] becomes input[numOfSlots] which in this case is input[2]. Since the last valid index of input is 1 you are comparing against garbage. You should have
if (input[i] != input[numOfSlots-i - 1])
Arrays in C++ are zero indexed, as i is initialised to 0, on the first iteration of the loop input[numOfSlots-i] is out of bounds.