Value assignment into array c++ - c++

I'm trying to create a array of prime numbers done by calculation. As a project to learn coding. Ultimately to build my own math library so this is something I can add onto at a variety of levels as I learn to code c++.
The following is code that works great for printing prime numbers to the screen based on the search range, but my totalPrimes iterator is stuck at 1. So each time it places the last prime found in the PrimeNumbers[1] position.
Any advice would be awesome.
#include <iostream>
#include <array>
std::array<long, 10000000> PrimeNumbers={0};
void isPrime(long x);
int main() {
for (long i = 1; i < 10; i++) {
isPrime(i);
}
for(int h = 0; h < 10; h++) {
std::cout << "\nSecond Prime is : " << PrimeNumbers[h];
}
}
void isPrime(long x) {
int count(0), totalPrimes(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
if (count == 1) {
++totalPrimes;
std::cout << '\n' << x << " is a Prime number";
PrimeNumbers[totalPrimes] = x;
}
}

You're initializing totalPrimes to 0 every time the function runs. You would need to have totalPrimes as a global variable, or better yet (because global variables can become problematic), set it equal to the first available member of PrimeNumbers before you do anything else in that function.

Keep track of a position along with your PrimeNumbers array.
size_t nLastPos=0;
...
for(size_t x = 0; 1000 > x; ++x)
{
if(isPrime(x))
{
PrimeNumbers[nLastPos++] = x;
}
}
for(size_t i = 0; nLastPos > n; ++n)
{/* print out number PrimeNumbers[n] */ }

It looks like you're having some trouble with variable scoping. The reason for your problem (as I noted in the comment) is that totalPrimes is local, so you're creating a new integer variable and setting it to 0 every time the function is called.
However, you've made PrimeNumbers global and are having the isPrime function modify it, which doesn't look like good practice.
All of this can be fixed with a little restructuring to make the code nicer:
#include <iostream>
#include <array>
bool isPrime(long x);
int main() {
std::array<long, 10000000> PrimeNumbers={0};
int totalPrimes = 0;
for (long i = 1; i < 10; i++) {
if (isPrime(i)) {
std::cout << '\n' << i << " is a Prime number";
PrimeNumbers[totalPrimes++] = i;
}
}
for(int h = 0; h < 10; h++) {
std::cout << h << " Prime is : " << PrimeNumbers[h] << std::endl;
}
}
bool isPrime(long x) {
int count(0);
for (long a = 1; a < x; a++) {
if ((x % a) == 0) {
count += 1;
}
}
return count == 1;
}

Your program can be re-structured little bit to make it easier to follow and debug.
Don't put things in isPrime other than the logic to decide whether a number is prime. Make sure it returns a bool. This will make the function a bit simpler and easier to debug.
Use the return value of isPrime in the calling function to perform other bookkeeping tasks.
The logic you have used to check whether a number is prime is incorrect. That needs to be fixed.
Here's an updated version of your posted code.
#include <iostream>
#include <array>
#include <cmath>
std::array<long, 10000000> PrimeNumbers={0};
bool isPrime(long x);
int main()
{
int totalPrimes = 0;
for (long i = 1; i < 10; i++)
{
if ( isPrime(i) )
{
std::cout << i << " is a Prime number" << std::endl;
PrimeNumbers[totalPrimes] = i;
++totalPrimes;
}
}
}
bool isPrime(long x) {
// 1, 2, and 3 are primes.
if ( x <= 3 )
{
return true;
}
// Even numbers are not primes.
if ( x % 2 == 0 )
{
return false;
}
// Check the rest.
long end = (long)std::sqrt(x);
for (long a = 3; a < end; a += 2) {
if ((x % a) == 0)
{
return false;
}
}
return true;
}
and its output:
1 is a Prime number
2 is a Prime number
3 is a Prime number
5 is a Prime number
7 is a Prime number
9 is a Prime number

Everybody is talking about how your totalPrimes variable is reset each time the function is called, and this is obviously true. You could return the value from the function and increment it from main, you could use global variables having the variable being defined outside of the function so that it's not reset each time inside the function or you could use
A static variable!
Take a look at this simple case. I have a function called up_two which increases the value of by two each time the function is called. The static variable int value has a memory of each time the function up_two() is called which increments value by two each time. If I were to use a just an integer it would always reset the value and have it be zero, which is what I initially defined it to be.
The advantage of using a static variable is that I can count how many times a function has been called, and I can keep my counter specific to a particular function.
#include <iostream>
using namespace std;
void up_two();
int main()
{
for(int i = 0; i < 10; i++)
{
up_two();
}
return 0;
}
void up_two()
{
static int value = 0;
cout << value << endl;
value += 2;
}
This program doesn't solve the particular problem that you want to solve, but if you figure out how the static variable is working, it should make your workflow easier.
The magic line here is this:
static int value = 0;
With it like this my program prints the following:
0
2
4
6
8
10
12
14
16
18
Without the static declaration, you just get 10 lines of zeroes
which is troublesome.
Hope that helps you optimize your program the way you want it to be.

Related

Wrong output- trying for if the number is Armstrong

I am new to coding and just starting with the c++ language, here I am trying to find the number given as input if it is Armstrong or not.
An Armstrong number of three digits is an integer such that the sum of the cubes of its digits is equal to the number itself. For example, 153 is an Armstrong number since 1^3 + 5^3 + 3^3 = 153.
But even if I give not an armstrong number, it still prints that number is armstrong.
Below is my code.
#include <cmath>
#include <iostream>
using namespace std;
bool ifarmstrong(int n, int p) {
int sum = 0;
int num = n;
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
if(sum==n){
return true;
}else{
return false;
}
}
int main() {
int n;
cin >> n;
int i, p = 0;
for (i = 0; n > 0; i++) {
n = n / 10;
}
cout << i<<endl;
if (ifarmstrong(n, i)) {
cout << "Yes it is armstorng" << endl;
} else {
cout << "No it is not" << endl;
}
return 0;
}
A solution to my problem and explantation to what's wrong
This code
for (i = 0; n > 0; i++) {
n = n / 10;
}
will set n to zero after the loop has executed. But here
if (ifarmstrong(n, i)) {
you use n as if it still had the original value.
Additionally you have a error in your ifarmstrong function, this code
while(num>0){
num=num%10;
sum=sum+pow(num,p);
}
result in num being zero from the second iteration onwards. Presumably you meant to write this
while(num>0){
sum=sum+pow(num%10,p);
num=num/10;
}
Finally using pow on integers is unreliable. Because it's a floating point function and it (presumably) uses logarithms to do it's calculations, it may not return the exact integer result that you are expecting. It's better to use integers if you are doing exact integer calculations.
All these issues (and maybe more) will very quickly be discovered by using a debugger. much better than staring at code and scratching your head.

How to get arbitrary return values in c++

I am trying to write divisor function, Which gives all divisor of given number. But in that I do not want any array rather I want to return every divisors one by one. Is it possible?
This is code :
auto allDivisor(int num){
for (int i=1; i<=num; i++){
if(num % i == 0){
return i;
}
}
But I got only first iterations result:
Enter integer number : 10 All divisior of 10 : 1
#include <iostream>
void allDivisor(int num, void (*callback)(int)) {
for (int i = 1; i <= num; i++) {
if (num % i == 0) {
callback(i);
}
}
}
int main() {
int num = 10;
std::cout << "All divisors of " << num << ": ";
allDivisor(num, [](int divisor) {
std::cout << divisor << " ";
});
std::cout << std::endl;
return 0;
}
The callback function is passed to the allDivisor function as an argument, and it is called once for each divisor of the input number.
the usual way is to call your function multiple times and each time it will return different divisor until the end is marked by some special return value like 0 ... the iteration can be done either by passing i as function parameter or have it as global or static variable but that would make your function thread unsafe prohibiting to use it in parallel (even in serial overlapped with other division) ... It would look like this:
int allDivisor(int num)
{
static int i=0;
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; return 0; }
}
and usage:
int d,X;
for (X=32;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
for (X=125;;)
{
d=allDivisor(X);
if (!d) break;
cout << d;
}
outputting this:
1
2
4
8
16
32
1
5
25
125
however be sure you always call the allDivisor until it returns 0 otherwise its next usage would be messedup (skipped first divisors until last i state) ... that could be repaired too for example like this (at cost of another static variable):
int allDivisor(int num)
{
static int i=0,n=0;
if (n!=num){ n=num; i=0; }
for (i++;i<=num;i++)
if ((num%i)==0) return i;
if (i>num){ i=0; n=0; return 0; }
}

How to print the b-th prime number coming after n?

I'm trying to write a c++ program which gets an integer n (n>=1 && n<=100000) from the user and puts the sum of its digits into b. The output needed is the b-th prime number coming after n. I'm an absolute beginner in programming so I don't know what's wrong with the for loop or any other code that it doesn't show the correct output. For example the 3rd prime number after 12 (1+2=3) is 19 but the loop counts the prime numbers from 2 instead of 12, so it prints 7 as result.
#include <iostream>
using namespace std;
bool isPrime(int n)
{
if(n <= 1)
return false;
for(int i = 2; i <= (n/2); i++)
if(n % i == 0)
return false;
return true;
}
int main()
{
long int n;
int b = 0;
cin>>n;
while(n >= 1 && n <= 100000){
b += n % 10;
n /= 10;
}
for(int i = n, counter = b; counter <= 10; i++)
if(isPrime(i)){
counter++;
if(i > n)
cout<<counter<<"th prime number after n is : "<<i<<endl;
}
return 0;
}
So one of the possible solutions to my question, according to #Bob__ answer (and converting it to the code style I've used in the initial code) is as follows:
#include <iostream>
using namespace std;
bool isPrime(long int number)
{
if(number <= 1)
return false;
for(int i = 2; i <= (number / 2); i++)
if(number % i == 0)
return false;
return true;
}
int sumOfDigits(long int number)
{
int sum = 0;
while(number >= 1 && number <= 100000)
{
sum += number % 10;
number /= 10;
}
return sum;
}
long int bthPrimeAfter(int counter, long int number)
{
while(counter)
{
++number;
if(isPrime(number))
--counter;
}
return number;
}
int main()
{
long int number;
cin>>number;
int const counter = sumOfDigits(number);
cout<<bthPrimeAfter(counter, number)<<"\n";
return 0;
}
As dratenik said in their comment:
You have destroyed the value in n to produce b in the while loop. When the for loop comes around, n keeps being zero.
That's a key point to understand, sometimes we need to make a copy of a variable. One way to do that is passing it to a function by value. The function argument will be a local copy which can be changed without affecting the original one.
As an example, the main function could be written like the following:
#include <iostream>
bool is_prime(long int number);
// ^^^^^^^^ So is `n` in the OP's `main`
int sum_of_digits(long int number);
// ^^^^^^^^^^^^^^^ This is a local copy.
long int nth_prime_after(int counter, long int number);
int main()
{
long int number;
// The input validation (check if it's a number and if it's in the valid range,
// deal with errors) is left to the reader as an exercise.
std::cin >> number;
int const counter = sum_of_digits(number);
std::cout << nth_prime_after(counter, number) << '\n';
return 0;
}
The definition of sum_of_digits is straightforward.
int sum_of_digits(long int number)
{
int sum = 0;
while ( number ) // Stops when number is zero. The condition n <= 100000
{ // belongs to input validation, like n >= 0.
sum += number % 10;
number /= 10; // <- This changes only the local copy.
}
return sum;
}
About the last part (finding the nth prime after the chosen number), I'm not sure to understand what the asker is trying to do, but even if n had the correct value, for(int i = n, counter = b; counter <= 10; i++) would be just wrong. For starters, there's no reason for the condition count <= 10 or at least none that I can think of.
I'd write something like this:
long int nth_prime_after(int counter, long int number)
{
while ( counter )
{
++number;
if ( is_prime(number) )
{
--counter; // The primes aren't printed here, not even the nth.
}
}
return number; // Just return it, the printing is another function's
} // responsabilty.
A lot more could be said about the is_prime function and the overall (lack of) efficiency of this algorithm, but IMHO, it's beyond the scope of this answer.

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.

remove odd numbers

I need to resolve this problme "Write a recursive function called removeCharge that receives an N number and returns a number that contains only the digits of the original number." I made it but now i don't know how to display the number in the same function.What can I do?
int newNumber=0;
int eliminareCifreImpare(int n){
if(n==0)
return 0;
eliminareCifreImpare(n/10);
int c=n%10;
if(c%2==0)
newNumber=newNumber*10+c;
}
I guess you are using a global variable because you don't properly understand how to return values from functions. You need to get a good understanding of how functions return values and how to use returned values before you try to write recursive functions.
Here's a working version
#include <iostream>
int eliminareCifreImpare(int n) {
if (n == 0)
return 0;
int newNumber = eliminareCifreImpare(n / 10);
int c = n % 10;
if (c % 2 == 0)
newNumber = newNumber * 10 + c;
return newNumber;
}
int main()
{
std::cout << eliminareCifreImpare(12345) << std::endl;
}