Print the maximum non perfect square - c++

I'm trying to make a c++ program that finds the maximum non perfect square in an array and print it, perfect square i.e. x = y^2 => 4 = 2^2.
Here is what I've tried and doesn't work for me, don't know why:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
sqrt(arr[i]);
if ((arr[i] * 10) % 10 == 0)
arr[i] = arr[1];
else
arr[i] = arr[0];
}
for (int i = 0; i < n; i++)
{
if (arr[0] < arr[i])
arr[0] = arr[i];
}
cout << arr[0] << endl;
return 0;
}
My logic is to take the square root of each array element and check if it's non-perfect or perfect. If we multiply the element by 10, then take modulus of 10, then we know whether it is an integer or decimal. For example: 2*10 = 20, 20%10 = 0 (perfect square), otherwise it is not perfect. Then, I stored each non-perfect square in arr[0], in the next loop I'm supposed to find the largest non perfect square and print it. What am I doing wrong?
PS:
Consider arr[variable] is valid, because it works in CodeBlocks. Thank you!

You lost the result of sqrt. sqrt(arr[i]) does not change arr[i]).
You improperly check if a square root is an integral. You should cast a result of sqrt to int, multiply it by itself and compare with arr[i].
I left you free to update your code properly yourself.

You can use this logic to find if a number is perfect-square or not, this is one way to find largest non perfect square of an array of positive numbers, initialize answer=-1 before you enter the loop, n is the size of the array
double answer = -1,temp;
for(int i=0;i<n;i++){
if((temp = array[i]) != (sqrt(array[i])*sqrt(array[i]))){
if(temp > answer){
answer = temp;
}
}
}

#include <iostream>
#include <cmath>
using namespace std;
int main () {
int n;
cin>>n;
int k[n];
double arr[n];
for (int i = 0 ; i < n ; i++){
cin>>k[i];
arr[i]=sqrt(k[i]);
int j = arr[i];
if (arr[i]==j){
arr[i]=0;
}
}
double m=0;
int index = 0;
for (int i = 0; i < n; i++){
if (arr[i]>m){
m=arr[i];
index = i;
}
}
cout << k[index];
}
Here is a code. We introduce a double, such that it can store the decimals. Then we introduce an integer. If the square root of the number is a decimal, it is not a perfect square. However, when I introduce this integer j, it will convert arr[i] to an integer. If the number is a perfect square, then arr[i] is an integer, and j==arr[i]. We do not want that, so we put that equal 0. We find the largest array, and mark the index. Then we print out the original number in the original array with that index. i have added this as float does not store every single decimal point.
To clarify: lets say arr[i]=4.55556. Then j=4. arr[i]!=j. If arr[i]=5, j=5, arr[i]=j, and then arr[i] is set to 0.

Related

Random numbers in the output

I've been coding in c++ for over a day now and I am currently stuck on this particular problem. I want to enter a integer and produce every prime numbers that are smaller than the given integer but the output always has random numbers that aren't prime. Here's the code:
#include <iostream>
#include <math.h>
using namespace std;
int check(int x){
bool prime = true;
if (x <= 1){
prime = false;
return 0;
}
for (int i = 2; i < x; i++){
if (x % i == 0){
prime = false;
return 0;
}
}
if (prime = true){
return x;
}
}
int main(){
int r;
cout << "Enter range: ";
cin >> r;
int primes[r];
int n = 0;
for (int i = 0; i < r; i++){
if (check(i) != 0){
primes[n] = i;
n++;
}
else{
}
}
for (int i : primes){
cout << i << endl;
}
}
Help me fix this problem. Thanks.
The problem in your code is that you check numbers in the range [0,r] and assume to find r prime numbers in that range. Thats of course not correct. For example when in the range [0,r] there are p prime numbers then your output will print the p prime numbers and then r-p uninitialized values (thats undefined behavior, the output of your code could be anything).
Change the last loop to
for (int i=0; i<n; ++i) {
cout << primes[i] << endl;
}
To see only entries of primes that you actually assigned a value in the loop before.
Also please consider that int primes[r]; is not standard C++. See here: Why aren't variable-length arrays part of the C++ standard?. Use std::vector for dynamically sized arrays. Actually in your code you do not need an array at all. You can simply print the prime numbers in the same loop where you check them:
if (check(i) != 0) { std::cout << i << "\n"; }
Moreover, your check is a little too complicated. You are using a flag that you don't need. The last if is wrong, because prime = true is assignment not comparison. However, that doesnt really matter because at that point prime is always true (if not you already returned), and prime=true does evaluate to true. The function can look like this:
int check(int x){
if (x <= 1){
return 0;
}
for (int i = 2; i < x; i++){
if (x % i == 0){
return 0;
}
}
return x;
}
This will also prevent the compiler from issuuing a warning for not returning from all branches. Note that you only need to check factors <= sqrt(x) because when there is a factor bigger than that there must also be a factor smaller than that.

Unique numbers using bitwise operators

In an array that has n numbers, all numbers are present twice except for two numbers. find them using bitwise operators.
i have tried it by taking a xor of the nos. in the array. then finding out the right most set bit in the xor.
then for all the nos. which have the same position of set bit in the array i have taken a xor of them together,
my code:-
#include<iostream>
using namespace std;
int main()
{
cout<<"enter the size of array."<<endl;
int n;
cin>>n;
int arr[n];
cout<<"enter the array elements."<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int myxor=0;
for(int i=0;i<n;i++)
{
myxor^=arr[i];
}
int set=0;
int k=0;
while(myxor)
{ k++;
set=myxor&1;
if(set)
{
break;
}
//k++;
myxor>>=1;
}
int t,p;
int xor2=0; int c=0;
int xor1=0;
for(int j=0;j<n;j++)
{
p=arr[j];
while(p)
{ c++;
t=p&1;
if(t)
{
break;
}
//c++;
p>>=1;
}
if(c==k)
{
xor1^=arr[j];
}
else{
xor2^=arr[j];
}
}
cout<<xor1<<endl;
cout<<xor2<<endl;
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int *arr = new int[n];
for (int i = 0; i < n; ++i)
cin >> arr[i];
int res = 0;
for (int i = 0; i < n; ++i)
res ^= arr[i];
/*
So far, we XOR-ed all elements in the array; the trick behind, though,
is that any two duplicates will eliminate themselves, so effectively
res now contains the two unique numbers XOR-ed together.
*/
/*
Now we need the index of a bit where these two unique numbers differ
i. e. the index of a one-bit in res; ANY one will do the trick,
so let's just pick the right most one...
*/
int set = 1;
while (!(set & res))
set <<= 1;
/*
Now the tricky part.
It is guaranteed that there are only 2 numbers which occur only once in the array.
Note that for any set bit in the xor of these two numbers,
that bit has to occur either in the 1st or 2nd.
Now traverse the array and check for which numbers this bit is set.
Note that for any number for which it is set, that number occurs twice unless it's one of the 2 unique numbers.
Hence if we keep "XOR-ing" `res` with numbers for which `set` bit is set, we acquire one of the 2 unique numbers.
Since the xor of both is stored in `res`, "XOR-ing" `ans` with `res` gives the 2nd unique number.
*/
int ans = res;
for (int i = 0; i < n; ++i)
if (arr[i] & set)
ans ^= arr[i];
cout << ans << ' ' << (ans ^ res) << endl;
}

(C++) Generate first p*n perfect square numbers in an array (p and n inputted from the keyboard)

I input p and n (int type) numbers from my keyboard, I want to generate the first p*n square numbers into the array pp[99]. Here's my code:
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int i, j, n, p, pp[19];
cout<<"n="; cin>>n;
cout<<"p="; cin>>p;
i=n*p;
j=-1;
while(i!=0)
{
if(sqrt(i)==(float)sqrt(i))
{
j++;
pp[j]=i;
}
i--;
}
for(i=0; i<n*p; i++)
cout<<pp[i]<<" ";
return 0;
}
But I am encountering the following problem: If I for example I enter p=3 and n=3, it will only show me the first 3 square numbers instead of 9, the rest 6 being zeros. Now I know why this happens, just not sure how to fix it (it's checking the first n * p natural numbers and seeing which are squares, not the first n*p squares).
If I take the i-- and add it in the if{ } statement then the algorithm will never end, once it reaches a non-square number (which will be instant unless the first one it checks is a perfect square) the algorithm will stop succeeding in iteration and will be blocked checking the same number an infinite amount of times.
Any way to fix this?
Instead of searching for them, generate them.
int square(int x)
{
return x * x;
}
int main()
{
int n = 0;
int p = 0;
std::cin >> n >> p;
int limit = n * p;
int squares[99] = {};
for (int i = 0; i < limit; i++)
{
squares[i] = square(i+1);
}
for (int i = 0; i < limit; i++)
{
std::cout << squares[i] << ' ';
}
}

The Sieve of Eratosthenes and Goldbach's Conjecture

The Sieve of Eratosthenes and Goldbach's Conjecture
Implement the Sieve of Eratosthenes and use it to find all prime
numbers less than or equal to one million. Use the result to
prove Goldbach's Conjecture for all even integers between four and
one million, inclusive.
Implement a function with the following declaration:
void sieve(int array[], int num);
This function takes an integer array as its argument. The array
should be initialized to the values 1 through 1000000. The
function modifies the array so that only the prime numbers remain;
all other values are zeroed out.
This function must be written to accept an integer array of any
size. You must should output for all primes numbers between 1 and
1000000, but when I test your function it may be on an array of a
different size.
Implement a function with the following declaration:
void goldbach(int array[], int num);
This function takes the same argument as the previous function
and displays each even integer between 4 and 1000000 with two
prime numbers that add to it.
The goal here is to provide an efficient implementation. This
means no multiplication, division, or modulus when determining if
a number is prime. It also means that the second function must find
two primes efficiently.
Output for your program: All prime numbers between 1 and 1000000
and all even numbers between 4 and 1000000 and the two prime
numbers that sum up to it.
DO NOT provide output or a session record for this project!
This is the code that I have so far, my problem is that it displays numbers higher than 1,000 as 1s, how can I go about this, thank you!
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
void sieve(int array[], int num);
void goldbach(int array[], int num);
const int arraySize = 1000000;
int nums[arraySize];
int main(){
for (int i = 0; i <= arraySize; ++i)
nums[i] = 1;
nums[0] = nums[1] = 0;
sieve(nums, arraySize);
for(int i = 0; i < 10000; ++i){
if (nums[i] > 0){
cout << nums[i] << " ";
}
}
goldbach(nums, arraySize);
return 0;
}
void sieve(int array[], int num) {
int squareR = (int)sqrt(num);
for(int i = 2; i <= squareR; ++i){
int k;
if(array[i]){
for(k = i*i; k <= num; k += i)
array[k] = 0;
}
if (array[i] == 1){
array[i] = i;
}
}
}
void goldbach(int array[], int num){
int i, r = 0;
for (i = 4; i <= num; i += 2){
for (int j = 2; j <= i/2; j++)
if (array[j] && array[i-j]) r ++;
}
}
my problem is that it displays numbers higher than 1,000 as 1s, how can I go about this
That's because you're not updating the values in the array above 1000, here:
for(int i = 2; i <= squareR; ++i){
...
if (array[i] == 1){
array[i] = i;
clearly the array's entries above squareR are not updated and remain at the value you initialized them, which is 1.
However I you don't need this update at all. You can drop it and simplify your code, keeping the array's entries as either 1 (for primes) or 0 (for non-primes). with this, and display your result like this (in main):
for(int i = 0; i < arraySize; ++i){
if (nums[i] != 0){
// cout << nums[i] << " "; // <-- drop this
cout << i << " "; // <-- use this
}
}

Modifying a dynamic 2D array in a function

I've got a function that accepts a dynamic multidimensional array (which is initialized to 0) as a parameter, and I'm trying to modify certain values within the array in my function.
The function that accepts the array as a parameter is supposed to simulate the roll of two dice and output the frequency distribution to the array I made that's initialized to zero.
The code for it is as follows:
#include <iostream>
#include <cstdlib>
using namespace std;
int** rollDie(int numRolls, unsigned short seed, int** &rollarray)
{
srand(seed);
int side1, side2;
while (numRolls > 0)
{
side1 = 1 + rand() % 6;
side2 = 1 + rand() % 6;
rollarray[side1][side2]++;
numRolls--;
}
return rollarray;
}
int** initializeArray(void)
{
int i, j;
int** m = new int*[6];
for (i = 0; i < 6; i++)
m[i] = new int[6];
for (i = 0; i < 6; i++)
for (j = 0; j < 6; j++)
m[i][j] = 0;
return m;
}
int main()
{
int numRolls;
unsigned short seed;
int ** a = initializeArray();
cout << "rolls?\n";
cin >> numRolls;
cout << "seed?\n";
cin >> seed;
int ** b = rollDie(numRolls, seed, a);
int i,j;
for (i = 0; i < 6; i++) {
for (j = 0; j < 6; j++) {
cout << b[i][j];
}
cout << "\n";
}
}
Code works for me with just a few issues (I had to guess how you defined a. Next time add that too):
In the printing you should print a space after every number (minor)
In the random, you choose index as 1+rand()%6, so from 1 to 6, but when you print you take indexes from 0 to 5! So your first row and first column will be 0.
Other than that it seems to work.
Only when one goes and does something else does the answer come to mind. I suspect you declared a as:
int a[6][6];
which is an array of 36 integers. In your function, though, you're declaring rollarray to be a pointer to an array of pointers to integers. All you need to do is change the function signature to:
int* rollDie(int numRolls, unsigned short seed, int* rollarray)
As cluracan said, you also want to use array indices in the range 0 to 5.
This is a good case for either the judicious use of print statements or stepping through with a debugger to see what's really going on.