Converting argv arguments to int - c++

I have tried atoi, strol, and stoi but none of them are working for me. I've even tried to subtract '0' from the char which I heard should work but that threw an error too. atoi gives me a Segmentation Fault, strol won't compile, and stoi gives me an std logic error. here is my entire program as of right now:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
bool isPrime(int);
int main (int argc, char *argv[])
{
const int size = 199;
int counter = 1;
int primeAry[size];
for (int i = 0; i < size; i++) // creates an array of prime numbers
{
if (isPrime(i))
{
primeAry[counter] = i;
counter++;
}
}
for (int j = 1; j <= argc; j++) // finds prime numbers by index of args and displays them
{
if (j == 1)
cout << "Last name is " << argv[j] << endl;
else
{
int temp = atoi(argv[j]);
cout << temp << " th prime number is " << primeAry[temp] << endl;
}
}
system("pause");
return 0;
}
bool isPrime(int num)
{
if(num <= 1)
return false;
else if (num <= 3)
return true;
else if (((num % 2) == 0) || (num % 3) == 0)
return false;
int i = 5;
while((i*i) <= num)
{
if ((num % i == 0) || ((num % (i + 2)) == 0))
return false;
i = i + 6;
}
return true;
}
And here is the result I get:
Last name is smith
1 th prime number is 2
2 th prime number is 3
3 th prime number is 5
Segmentation Fault
I've been working on this forever and I've searched every forum that I could find but I can't figure out what I'm missing.

Segmentation Fault**
You get segmentation fault when you pass NULL to atoi. This is happening because your loop bounds are incorrect. This:
for (int j = 1; j <= argc; j++)
should instead be
for (int j = 1; j < argc; j++)
In C, you should treat all loops with <= terminating condition with extreme suspicion. More often than not that's where the bug is hiding.

Related

print all the prime numbers upto an upperlimit

#include<iostream>
using namespace std;
int main(){
int n=5;
int i = 2;
for (i; i <= n; i++)
// for all num to n
{
int j = 2;
bool divide = false;
for (j; j <= n - 1; j++)
// for checking each num
{
if (i % j == 0)
{
divide = true;
break;
}
}
if (divide == false)
{
cout << i << " ";
}
}
return 0;
}
my Q is that
//please tell me why it is not working
//it is expected to give ans 2,3,5 which it is not giving why???
maybe I found the issue.
I think that the problem here is:
for (j; j <= n - 1; j++)
Here you did j<=n-1;
So to fix this just do:
for(j; j < i; j++){
//this should fix
So everything should look like this:
#include<iostream>
using namespace std;
int main() {
int n = 5;
int i = 2;
//check prime numbers starting from i and max n using for loop
for (i = 2; i <= n; i++) {
bool divide = false;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
divide = true;
break;
}
}
if (!divide) {
//!divide is equal to divide=false
cout << i << " ";
}
}
}

How to compare elements in an array for equality?

I've come across this problem where I have to transform a number from the decimal system to the binary and compare if the numbers are equal
Example:
7 is becoming 111
The output is false
and where 5 is 101
The output is true
I've figured out how to transform the numbers with an array
But have no idea how to compare them
#include<iostream>
using namespace std;
int main()
{
int num;
cin >> num;
int arr[8] = {};
if ((num >= 0) && (num <= 255))
{
while (num != 0)
{
for (int i = 0; i < 8; i++)
{
if (num % 2 == 0)
arr[i] = 0;
else
{
arr[i] = 1;
}
num = num / 2;
}
}
for (int i = 7; i >= 0; i--)
cout << arr[i];
cout << endl;
}
else
{
cout << "error" << endl;
return 1;
}
system("pause");
return 0;
}

Prime Number finding algorithm returns weird values

I am beginning to learn c++, and was working through the Project Euler challenges, and #7 asks you to find all prime numbers within a given range. After online research i decided to try using Sieve of Erastothenes, however with the code i have set up, i currently get weird values such as )2, 0) when i ask for 2 primes, and (2, 4, 5, 5) when i input 5.
#include <iostream>
#include <vector>
#include <math.h>
#include <bits/stdc++.h>
using namespace std;
int main(){
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = {2};
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++){
primes.push_back(i);
}
for (int i = 0; i < end_point; i++){
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
primes[i];
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i+1; j < primes.size(); j++){
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if(primes[j] % primes[i] == 0){
primes.erase (primes.begin() + (j-1));
}
else{}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++){
cout << primes[k] << ", ";
}
}
}
You shouldn't remove element from array when you traverse it. You can try it by marking.
example:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
//creates a vector to store all values, that will eventually be whittled down to primes
vector<int> primes = { 2 };
//adds all numbers between 2 and chosen end point to the vector
for (int i = 3; i <= end_point; i++) {
primes.push_back(i);
}
for (int i = 0; i < end_point; i++) {
//starts at the first value (always 2), and feeds it into the next for loop
//once the next loop is done, it moves on to the next value in the loop and feeds that in
int val = primes[i];
// to ensure the value is not zero
if (val == 0)
continue;
//looks at values in the vector, starting with the next value in the vector
for (unsigned int j = i + 1; j < primes.size(); j++) {
//checks if the value at [j] is divisible by the value at [i]
//if it is, this deletes it from the vecotr
//if not, it moves on to the next value in the vector
if (primes[j] > 0 && primes[j] % val == 0) {
// set the value zero to element of array.
primes[j] = 0;
}
}
//prints out all of the primes in the specified range
cout << "Primes are: ";
for (unsigned int k = 0; k <= primes.size(); k++) {
if (primes[k] > 0) // output the value which greater then zero.
cout << primes[k] << ", ";
}
}
return 0;
}
You delete wrong element. This is right:
primes.erase(primes.begin() + j);
Your last loop in wrong place. Take it out of previous 'for loop'. And you go after last element. Should be:
k < primes.size();
not
k <= primes.size();
=== Now it works properly ===
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
int main() {
int end_point;
cout << "how many prime numbers would you like to find?\n";
cin >> end_point;
vector<int> primes = { 2 };
for (int i = 3; i <= end_point; i++) {
primes.push_back(i);
}
for (int i = 0; i < end_point; i++) {
for (unsigned int j = i + 1; j < primes.size(); j++) {
if (primes[j] % primes[i] == 0) {
primes.erase(primes.begin() + j);
}
else {}
}
}
cout << "Primes are: ";
for (unsigned int k = 0; k < primes.size(); k++) {
cout << primes[k] << ", ";
}
return 0;
}
you can check prime from 2 to the sqrt of that number. this will omit duplicates and extra checks.
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<int> getPrimes(int start, int end){
if( start <0 || end < 0 || end < start ){
return {};
}
int max = 0;
bool isPrime = true;
vector<int> prims = {};
for( int i = start ; i <= end ; i++ ){
max = sqrt(i);
isPrime = true;
for(int j = 2 ; j <= max ; j++ ){
if( i % j == 0 ){
isPrime = false;
break;
}
}
if(isPrime){
prims.push_back(i);
}
}
return prims;
}
int main()
{
vector<int> prims = getPrimes(0,100);
for(int n : prims) {
cout << n << '\n';
}
return 0;
}
Sqrt Reason:
imagine you want to find out that 17 is a prime number or not. the simplest way is to loop from 0 to 17 to check its multiples. but it doesn't needed to do that. the sqrt of 17 is almost 4. so you check the multiples until the number 4. the next number is 5. from 5 to 17, all the multiples that their results is smaller that 17 is from 4 to 0. because 5 * 5 is 25 . even 5 * 4 is 20. so all multiples going to be repetitious.
now you can just check multiples from 2 to square root of that number to find out the number is a prime number or not

list of prime numbers between 1 and 100

I want to find the list of prime numbers, I try this code but it doesn't show me anything:
#include <iostream>
using namespace std;
int main()
{
int n, i;
std::cout << "Liste des nombres premiers : " << std::endl;
for (n = 1; n < 100; n++) {
for (i = 2; i < n; i++) {
if (n % i == 0)
std::cout << n << " ";
}
}
return 0;
}
I don't like your code at all. Try to do this: create a function that tells you if a number is prime, and then go with a for loop through all numbers from 1 to 100, and check with the function if they are prime.
Here is an easy to remember function (for natural numbers):
bool isPrime(int n)
{
if (n <= 1)
return 0;
if (n == 2)
return 1;
if (n%2 == 0)
return 0;
for (int i=3; i*i <= n; i+=2)
if (n%i == 0)
return 0;
return 1;
}
This function returns 1 if the number is prime, and returns 0 if it isn't.
The idea is this:
If n is 0 or 1, it is not prime.
If n is 2, it is prime.
If n is a multiple of 2, but it isn't 2, it is not prime.
Then, you have to check if n has any divisors until you get to square root of n (i * i <= n)
To correct program errors:
Initialize the value of n as 2.
And print when i is equal to n not when n % i is 0. It should be rather n % i == 0 then break.
Change i < n to i <= n.
Try the first approach (used sqrt()):
#include <iostream>
#include <cmath>
int main(void)
{
for (int i = 2; i < 100; i++) {
if (i == 2 || i == 3) { // if number is 2 or 3, then prints it
std::cout << i << ' ';
}
for (int j = 2; j * j <= i; j++)
{
if (i % j == 0) break;
else if (j + 1 > sqrt(i)) std::cout << i << ' ';
}
}
return 0;
}
Alternative approach:
#include <iostream>
int main(void)
{
for (int n = 2; n < 100; n++)
for (int i = 2; i <= n; i++)
if (i == n) std::cout << i << ' ';
else if (n % i == 0) break;
return 0;
}

prime seive algorithm giving a runtime error

I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}