Finding perfect number - c++

Finding perfect number in an integer range.
Firstly I wrote this code:
#include <stdio.h>
int main() {
int ara[5] = { 6, 28, 496, 2128, 33550336 };
int num, i, l, j, kase;
scanf("%d", &kase);
for (l = 0; l < kase; l++) {
scanf("%d", &num);
j = 1;
for (i = 0; ara[i] <= num; i++) {
printf("%d\n", ara[i]);
}
}
return 0;
}
but when I enter a larger number such as:
2//kase
40000000//input_1
outputs:
6
28
496
2128
33550336
1
0
7
76596795 (input_2) outputs:
6
28
496
2128
33550336
1
1
7
when I use if condition in loops it works perfectly well.
#include <stdio.h>
int main() {
int ara[5] = { 6, 28, 496, 8128, 33550336 };
int i, l, kase;
int num;
scanf("%d", &kase);
for (l = 0; l < kase; l++) {
scanf("%d", &num);
for (i = 0; i < 5; i++) {
if (ara[i] <= num) {
printf("%d\n", ara[i]);
} else {
break;
}
}
}
return 0;
}
as like: 1//kase 40000000//input outputs: 6, 28, 8128, 33550336.
It'll be a great pleasure for me if anyone tell me some details about this.

This is because in the first case, your control stays in the loop even as the value of i reaches and crosses 5.
for(i = 0; ara[i] <= num; i++)
{
printf("%d\n", ara[i]);
}
Suppose you input 40000000. Then, all elements in the array satisfy the condition ara[i] <= num. But this is the sole condition for exiting the loop, due to which you stay in the loop i=5,6,7... and so on. The rest of the output values are garbage values.
In the second case, you are ensuring that i<5, so the problem is resolved. You could do this
for(i = 0; i < 5 && ara[i] <= num; i++)
{
printf("%d\n", ara[i]);
}

Related

I have to move negative elements at end of array and in some cases like provided below I'm getting a garbage vale instead of negative element

#include <stdio.h>
#include <iostream>
using namespace std;
#define MAX 10
int main()
{
//code
int n,i=0,arr[MAX];
cin>>n;
for(int i =0;i<n;i++)
{
cin>>arr[i];
}
int j=1;
while(i<n&&j<=n)
{
if(arr[i]>0)
{
i++;
j++;
}
else if(arr[i]<0 && arr[j]>0)
{
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
}
else if(arr[i]<0 && arr[j]<0)
{
j++;
}
else
{
i++;
}
}
for(i=0;i<n;i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
INPUT
4
-8
-6
7
8
OUTPUT
7 8 4196864 -6
How can I resolve this?
I have to move negative elements at end of array and in some cases like provided below I'm getting a garbage value instead of negative element. Some cases are working but many are not specially the ones with two consecutive negative elements with following positive element.
This answer is posted for anyone looking for a C++ solution using algorithm functions. The function that gets the job done is std::partition:
#include <iostream>
#include <algorithm>
#define MAX 10
int main()
{
int n = 4;
int arr[MAX] = {-8, -6, 7, 8};
std::partition(arr, arr + n, [&](int val) { return val >= 0;});
for (int i = 0; i < n; ++i)
std::cout << arr[i] << " ";
}
Output:
8 7 -6 -8
If you want to keep the original, relative order of the elements, you can use std::stable_partition:
#include <iostream>
#include <algorithm>
#define MAX 10
int main()
{
int n = 4;
int arr[MAX] = {-8, -6, 7, 8};
std::stable_partition(arr, arr + n, [&](int val) { return val >= 0;});
for (int i = 0; i < n; ++i)
std::cout << arr[i] << " ";
}
Output:
7 8 -8 -6
From the code you've posted, it looks like you are using C, but with cout and cin borrowed from C++.
As PaulMcKenzie already posted a one-line C++ solution, here is how you would write it your way (the C way):
#include <stdio.h>
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
void move_neg_to_end(int *arr, int n)
{
int start, end = n-1;
for (start = 0; start <= end; start++) {
if (arr[start] >= 0)
continue;
while (start < end && arr[end] < 0)
end--;
if (start >= end)
break;
swap(&arr[start], &arr[end]);
end--;
}
}
Use it like:
int main()
{
int arr[] = {4, -8, -6, 7, 8, -3, 2};
int n = sizeof(arr) / sizeof(*arr);
move_neg_to_end(arr, n);
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
EDIT: Here is what's wrong with your code:
1- Don't mix <stdio> and <iostream>. You are using either C or C++, not both. So just choose one of them. If you are using C++ (your case), then go for <iostream>.
2- Avoid using namespace std because it pollutes the global namespace. Use std:: prefix instead, or if you want "shortcuts" using std::cin.
3- Avoid macros like #define MAX 10 and use const int max = 10 instead. Macros make debugging a pain.
4- In C++ use std::array or std::vector. Avoid raw arrays.
5- cin >> n... what if n exceeds MAX?
6- j <= n causes your array to overflow.
7- The logic of your code is wrong. j should start from n-1, not from 0. Here is how you can do it:
If arr[i] >= 0 go to the next element.
If arr[i] < 0 and arr[j] < 0 then keep decrementing j until it finds a positive element or is lesser than or equal to i.
If arr[i] < 0 and arr[j] >= 0 then swap arr[i] and arr[j].
Goto step 1 if i <= j.

Arrays - Sum Of Two numbers as arrays of digits

Take as input N, the size of array. Take N more inputs - digits between 0 and 9 - and store that in an array. Take as input M, the size of second array and take M more input digits and store that in second array. Write a function that returns the sum of the numbers represented by the two arrays. Print the value returned.
Input:
4
1 0 2 9
5
3 4 5 6 7
Output:
3, 5, 5, 9, 6, END
Below is the code I have written for it, but it's not giving any result rather it crashes.
using namespace std;
int main()
{
int tsum,n,m,s,carry=0;
cin>>n;
int a[n],sum[]={0};
for(int i=0; i<n; i++)
{
cin>>a[i];
}
cin>>m;
int b[m];
for(int i=0; i<m; i++)
{
cin>>b[i];
}
s=max(n,m);
sum[s] = {0};
while(n>0 and m>0)
{
tsum=a[n]+b[m]+carry;
sum[s] = tsum%10;
carry = tsum/10;
n--;
m--;
s--;
}
if(n>m)
{
while(n>0)
{
tsum=a[n]+carry;
sum[s] = tsum%10;
carry = tsum/10;
n--;
s--;
}
}
if(m>n)
{
while(m>0)
{
tsum=b[m]+carry;
sum[s] = tsum%10;
carry = tsum/10;
m--;
s--;
}
}
for (int i=1; i<s; i++)
{
cout<<sum[i]<<", ";
}
cout<<"END";
return 0;
}```

How can I find the index of two integers that have the smallest difference from a series of integers?

i've a problem that asks me to print the index of the integers whose difference is smallest. If the inputs are 5 and 10 12 13 15 10, I have to print 5 1. The problem is here. Below is my code:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
int n;
int temp=1005,pos1=0,pos2=0;
cin>>n;
vector <int> vec;
for(int i=0;i<n;i++){
int in; cin>>in;
vec.push_back(in);
}
for(int i=0;i<n;i++){
for(int j=1;j<n;j++){
if(i==j)break;
int ans=abs(vec[i]-vec[j]);
cout<<i+1<<"-"<<j+1<<" = "<<ans<<endl;
if(ans<temp){
temp=ans;
pos1=i,pos2=j;
}
}
}
cout<<pos1+1<<" "<<pos2+1<<endl;
return 0;
}
Here's my solution in C. Remember that you need only be concerned with neighboring elements and that the soldiers are organized in a circle. Also, I found it a bit weird that the solution is asking for indexes starting at 1 and not 0.
#include <stdio.h>
#define ABS(n) ((n) * (((n) > 0) - ((n) < 0)))
void solution(int n, int soldiers[static 2])
{
int indexA = 1,
indexB = 2,
minDiff = ABS(soldiers[0] - soldiers[1]),
heightDiff;
for (int i = 1; i < n; i++)
{
if ((heightDiff = ABS(soldiers[i] - soldiers[(i + 1) % n])) < minDiff)
{
minDiff = heightDiff;
indexA = i + 1;
indexB = ((i + 1) % n) + 1;
}
}
printf("%d %d\n", indexA, indexB);
}
int main()
{
solution(5, (int[5]){10, 12, 13, 15, 10});
//5 1
solution(4, (int[4]){10, 20, 30, 40});
//1 2
return 0;
}
The soldiers stand in a circle and you are supposed to look at soldiers standing next to each other.
This means you don't need the j loop. You can simply compare vec[i] with vec[(i+1) % n].

Get the max element in an array that ends with a 0

So, I am writing a code which creates an array with an elements and amount of elements written by user and then a code generates a biggest value which last digit is zero. So, I have accomplished a step of writing an array which is elements entered by user. The hardest part( for me) is to complete a code which generates biggest value which last digit is zero. So yeah, I need an advice in completing this code. Thank you.
for example :
An array - 2 20 25 300 55555
The biggest number which last digit is zero is 300
So yeah, I need an advice in completing this code. Here is a code what I have done so far :
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int GetAmount() {
int howmany;
printf("Enter amount of elements - ");
scanf_s("%i", &howmany);
return howmany;
}
void GetArray(int a[], int n) {
printf("Enter elements - \n");
for (int i = 0; i < n; i++)
{ printf("%i ->", i);
scanf_s("%i", &a[i]);
}
}
int LastDigitZero(int n[], int a) {
for (int i = 0; i < a; i++)
{
if (n[i] % 10 == 0) {
return 0;
}
}
}
int maxvalue(int a[], int n) {
int temp = 0;
for (int i = 0; i < n; i++)
{
if (a[i] > temp) {
temp = a[i];
}
}
return temp;
}
void main() {
int amount = GetAmount();
int array[100];
GetArray(array, amount);
int max = maxvalue(array, amount);
printf("Max Value is %i\n", max);
}
Thank you for your attention, have a nice day! :)
It works! That's how it looks!
#include "stdafx.h"
#include <stdlib.h>
#include <windows.h>
#include <time.h>
int GetAmount() {
int howmany;
printf("Enter amount of elements - ");
scanf_s("%i", &howmany);
return howmany;
}
void GetArray(int a[], int n) {
printf("Enter elements - \n");
for (int i = 0; i < n; i++)
{ printf("%i ->", i);
scanf_s("%i", &a[i]);
}
}
int maxvalue(int a[], int n) {
int temp = 0;
for (int i = 0; i < n; i++)
{
if (a[i] % 10 == 0 && a[i] > temp) {
temp = a[i];
}
}
return temp;
}
void main() {
int amount = GetAmount();
int array[100];
GetArray(array, amount);
int max = maxvalue(array, amount);
printf("The biggest number which last digit is zero is %i\n ", max);
system("pause");
}
Thank you guys for the answers! That was fast!!! :)
You almost have it. First any number that ends in 0 mod 10 is 0 so that is how you can check if the last digit is 0. With that you would change maxvalue() to
int maxvalue(int a[], int n) {
int temp = a[0];
for (int i = 1; i < n; i++)
{
if (a[i] % 10 == 0 && a[i] > temp) {
temp = a[i];
}
}
return temp;
}
I also made a change to set temp to the value of a[0] as if your array is all negative numbers then 0 would be the largest number. Since temp is already a[0] we can then start the for loop at 1.
You should check if there is a solution, in this example you could check that the value returned by maxValue finishes by 0 (if none of the values finishes by 0 then it would return a[0]):
int maxValue(int a[], int n) {
int temp= a[0]
for (int i(1); i<n;i++) {
if (a[i] % 10 == 0 && (temp % 10 != 0 || a[i] > temp )) temp = a[i];
}
return temp;
}

How can I iterate through every possible combination of n playing cards

How can I loop through all combinations of n playing cards in a standard deck of 52 cards?
You need all combinations of n items from a set of N items (in your case, N == 52, but I'll keep the answer generic).
Each combination can be represented as an array of item indexes, size_t item[n], such that:
0 <= item[i] < N
item[i] < item[i+1], so that each combination is a unique subset.
Start with item[i] = i. Then to iterate to the next combination:
If the final index can be incremented (i.e. item[n-1] < N-1), then do that.
Otherwise, work backwards until you find an index that can be incremented, and still leave room for all the following indexes (i.e. item[n-i] < N-i). Increment that, then reset all the following indexes to the smallest possible values.
If you can't find any index that you can increment (i.e. item[0] == N-n), then you're done.
In code, it might look something vaguely like this (untested):
void first_combination(size_t item[], size_t n)
{
for (size_t i = 0; i < n; ++i) {
item[i] = i;
}
}
bool next_combination(size_t item[], size_t n, size_t N)
{
for (size_t i = 1; i <= n; ++i) {
if (item[n-i] < N-i) {
++item[n-i];
for (size_t j = n-i+1; j < n; ++j) {
item[j] = item[j-1] + 1;
}
return true;
}
}
return false;
}
It might be nice to make it more generic, and to look more like std::next_permutation, but that's the general idea.
This combinations iterator class is derived from the previous answers posted here.
I did some benchmarks and it is a least 3x faster than any next_combination() function you would have used before.
I wrote the code in MetaTrader mql4 to do testing of triangular arbitrage trading in forex. I think you can port it easily to Java or C++.
class CombinationsIterator
{
private:
int input_array[];
int index_array[];
int m_indices; // K
int m_elements; // N
public:
CombinationsIterator(int &src_data[], int k)
{
m_indices = k;
m_elements = ArraySize(src_data);
ArrayCopy(input_array, src_data);
ArrayResize(index_array, m_indices);
// create initial combination (0..k-1)
for (int i = 0; i < m_indices; i++)
{
index_array[i] = i;
}
}
// https://stackoverflow.com/questions/5076695
// bool next_combination(int &item[], int k, int N)
bool advance()
{
int N = m_elements;
for (int i = m_indices - 1; i >= 0; --i)
{
if (index_array[i] < --N)
{
++index_array[i];
for (int j = i + 1; j < m_indices; ++j)
{
index_array[j] = index_array[j - 1] + 1;
}
return true;
}
}
return false;
}
void get(int &items[])
{
// fill items[] from input array
for (int i = 0; i < m_indices; i++)
{
items[i] = input_array[index_array[i]];
}
}
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
// driver program to test above class
#define N 5
#define K 3
void OnStart()
{
int x[N] = {1, 2, 3, 4, 5};
CombinationsIterator comboIt(x, K);
int items[K];
do
{
comboIt.get(items);
printf("%s", ArrayToString(items));
} while (comboIt.advance());
}
Output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
#include <iostream>
#include <vector>
using namespace std;
class CombinationsIndexArray {
vector<int> index_array;
int last_index;
public:
CombinationsIndexArray(int number_of_things_to_choose_from, int number_of_things_to_choose_in_one_combination) {
last_index = number_of_things_to_choose_from - 1;
for (int i = 0; i < number_of_things_to_choose_in_one_combination; i++) {
index_array.push_back(i);
}
}
int operator[](int i) {
return index_array[i];
}
int size() {
return index_array.size();
}
bool advance() {
int i = index_array.size() - 1;
if (index_array[i] < last_index) {
index_array[i]++;
return true;
} else {
while (i > 0 && index_array[i-1] == index_array[i]-1) {
i--;
}
if (i == 0) {
return false;
} else {
index_array[i-1]++;
while (i < index_array.size()) {
index_array[i] = index_array[i-1]+1;
i++;
}
return true;
}
}
}
};
int main() {
vector<int> a;
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
int k = 3;
CombinationsIndexArray combos(a.size(), k);
do {
for (int i = 0; i < combos.size(); i++) {
cout << a[combos[i]] << " ";
}
cout << "\n";
} while (combos.advance());
return 0;
}
Output:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
I see this problem is essentially the same as the power set problem. Please see Problems with writing powerset code to get an elegant solution.