my programming teacher gave me this problem to code it in c :
given array of N integers A and a number K. During a turn the maximal value over all Ai is chosen, let's call it MAX. Then Ai =
MAX - Ai is done for every 1 <= i <= N. Help Roman to find out how will the array look like after K turns.
Input
The numbers N and K are given in the first line of an input. Then N integers are given in the second line which denote the array A.
Output
Output N numbers on a single line. It should be the array A after K turns.
Constraints
* 1 <= N <= 10^5
* 0 <= K <= 10^9
* Ai does not exceed 2 * 10^9 by it's absolute value.
Example
Input:
4 1
5 -1 7 0
Output:
2 8 0 7
and my code to this problem is :
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
long int Max(long int *arr, int low, int high)
{
long int max,i;
max = arr[low];
for(i=0;i<=high;i++)
{
if(max<=arr[i])
max = arr[i];
}
return max;
}
/* Driver program to test above function */
int main()
{
long int max,*arr;
long int n,k,c1,c2,c3,i,j;
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
c3 = 2*c2;
scanf("%ld %ld",&n,&k);
if(n<1||n>c1)
exit(1);
else if(k<0||k>c2)
exit(1);
else
{
arr = (long int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{
scanf("%ld",&arr[i]);
if(abs(arr[i])>c3)
exit(1);
}
if(k%2 == 0)
{
for(i=0;i<2;i++)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
if(abs(arr[j])>c3)
exit(1);
}
}
}
else if(k%2 != 0)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
/*if(abs(arr[j])>c3)
exit(1);*/
}
}
/* for(m=0;m<n;m++)
printf("%ld ",arr[m]);
printf("\n");*/
for(i=0;i<n;i++)
printf("%ld ",arr[i]);
printf("\n");
}
return 0;
}
i executed this code on gcc compiler in ubuntu, it is working perfectly with all the constraints satisfied but when I uploaded this code on my teacher's portal which has a compiler and executed the code, it said Runtime error -
nzec which means a non-zero exception which is used to signify that main() does not have "return 0;" statement or exception thrown by c++ compiler.
Please, can anyone help me what is wrong in my code as there is a return 0; statement in my code. Please Help.
Everyone has pointed out multiple use of exits ... Can I reduce them using any other way in place of exit()?
My guess is that it has to do with the various exit(1) statements you have for error conditions.
As pointed out by Dave Costa, exit(1) could be the cause
Another possible problem is the size of the allocated array:
arr = (long int *)malloc(sizeof(int)*n);
should be:
arr = malloc(sizeof(long int)*n);
And note that you don't need to use pow for constants:
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
could be replaced with:
c1 = 1e5L;
c2 = 1e9L;
Related
background: I was writing a c++ program to solve this problem:
For a positive integer N, the digit-sum of N is defined as the sum of N itself and its digits. When M
is the digitsum of N, we call N a generator of M.For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of
256. Not surprisingly, some numbers do not have any generators and some numbers have more than one generator. For example, the generators of 216 are 198 and 207.
You are to write a program to find the smallest generator of the given integer.
Input
Your program is to read from standard input.
The input consists of T test cases.
The number of test cases T is given in the first line of the input.
Each test case takes one line containing an integer N, 1 ≤ N ≤ 100, 000.
Output
Your program is to write to standard output.
Print exactly one line for each test case.
The line is to contain a generator of N for each test case.
If N has multiple generators, print the smallest.
If N does not have any generators, print ‘0’.
my problem: the program below always terminated with status -1073740940, I wonder why and need some help
int main()
{
int* ans = new int[100005]();
int y;
int i_op;
for(int i = 1; i < 100001; ++i){
y = i;
i_op = i;
while(i_op){
y += i_op%10;
i_op /= 10;
}
if(ans[y] == 0 || i < ans[y]){
ans[y] = i;
}
}
int t;
int n;
cin >> t;
for(int i = 0; i < t; ++i){
cin >> n;
cout << ans[n] << endl;
}
//========================
//problem occurs here //after doing all output, the process terminated with status -1073740940
//========================
delete[] ans;
return 0;
}
input data: (both terminated with status -1073740940)
10
70587
38943
37061
95352
84205
96532
21150
26337
97804
65891
and
100000
1
2
……
100000
You may be writing past the end of your array during the computation and corrupting something. What happens for i = 99999? I don't think 100005 is quite enough to contain that. Let's check:
#include <stdio.h>
int main() {
int i = 99999;
int y = i;
int i_op = i;
while(i_op){
y += i_op%10;
i_op /= 10;
}
printf("%d\n", y);
}
Outputs 100044. Indeed.
I am just beginning with dynamic programming, and I have just attempted a simple question based on DP, on Spoj. Link - http://www.spoj.com/problems/MST1/
Here is the question statement -
On a positive integer, you can perform any one of the following 3
steps.
1.) Subtract 1 from it. ( n = n - 1 )
2.) If its divisible by 2, divide by 2. ( if n % 2 == 0 , then n = n / 2 )
3.) If its divisible by 3, divide by 3. ( if n % 3 == 0 , then n = n / 3 )
Given a positive integer n and you task is find the minimum number of
steps that takes n to one.
Input:
The input contains an integer T (1 ≤ T ≤ 100) number of test cases.
Second line input is N (0 < N ≤ 2*10^7 ) that indicates the positive
number.
Output:
For each case, print the case number and minimum steps.
Here's my code -
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
// Memo Function returns the smallest number of steps possible for integer a
int memo(int a, int mem[]);
int mem[20000010];
int main() {
int t;
scanf("%i", &t);
for(int i = 1; i <= t; i++) {
int n;
scanf("%i", &n);
memset(mem, -1, sizeof(mem));
mem[1] = 0;
printf("Case %i: %i\n", i, memo(n, mem));
}
return 0;
}
int memo(int a, int mem[]) {
if (mem[a] != -1) return mem[a]; // If the value of smallest steps have already been calculated
int r; // Current Lowest number of steps
r = memo(a - 1, mem) + 1;
if (a % 2 == 0) r = min(r, memo(a/2, mem) + 1);
if (a % 3 == 0) r = min(r, memo(a/3, mem) + 1);
mem[a] = r;
return r;
}
I have looked up this error on the internet and here on StackOverflow, and I have found that it may occur when we are trying to access the memory that has not been allocated, for example accessing the 11th element of a 10 element array. But I don't think that's the case here.
Also, I think the upper limit of the question is 2*10^7, also the array is global, so it shouldn't be an issue. Maybe there's some issue in the way I am using the memset function? I really don't know!
Any help will be appreciated! Thanks for reading!
Your DP idea is correct but your code is not working for a large inputs (e.g. 1x10^6, or the upper boundary, 2x10^7).
By changing your code a little, you can pre-compute every answer and then output only the ones you are interested in. It will be not very time-consuming because of the dynamic programming fashion of the problem, i.e., a complex problem can be solved as a combination of one or more previously solved problems.
int main()
{
// Initialize DP array
memset(mem, -1, sizeof(mem));
mem[1] = 0;
// Pre-compute every possible answer
for(int i = 2; i <= 20000000; i++)
mem[i] = memo(i);
// Read the number of test cases
int t;
scanf("%d", &t);
// Print only the desired answer, ie, mem[n]
for(int i = 1; i <= t; i++) {
int n;
scanf("%d", &n);
printf("Case %d: %d\n", i, mem[n]);
}
return 0;
}
I got an ACCEPTED with this approach.
Another tip: since your DP array is global, you do not have to pass it to the DP function every time.
Alright please go easy. Just learning C++ and first also question here. I've written a program to list all Armstrong numbers below 1000. While I have read the Wikipedia article on narcissistic numbers, I'm only looking for 3-digit ones. Which means I only care for the sum of the cubes of the digits.
It works by executing a for loop for 1 to 1000, checking whether the indexing variable is armstrong or not using a user defined function and printing it if it is. The user defined function works simply by using a while loop to isolate digits and matching the sum of the cubes to the original number. If it is true, then returns 1 otherwise return 0.
The problem is, I'm getting abolutely no numbers in the output. Only the cout statement in void main() appears and the rest is blank. Tried to debug as much as I could. Complier is Turbo C++. Code-
#include<iostream.h>
#include<conio.h>
int chk_as(int);//check_armstrong
void main()
{
clrscr();
cout<<"All Armstrong numbers below 1000 are:\n";
for(int i=1;i<=1000;i++)
{
if (chk_as(i)==1)
cout<<i<<endl;
}
getch();
}
int chk_as (int n)
{
int dgt;
int sum=0,det=0;//determinant
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}
The problem is that you are dynamically changing the value of n in your method, but you need its original value to check the result.
Add in a temporary variable, say, t.
int t = n;
while (t!=0)
{
dgt=t%10;
t=t/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
// ... etc.
EDIT: Nevermind... this was wrong
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
This runs forever as n never reaches 0.
The problem is, that in the end of the loop
while (n!=0)
{
dgt=n%10;
n=n/10;
sum+=(dgt*dgt*dgt);
}
n is 0, so the condition if (sum==n) is never true.
Try something like :
int chk_as (int n)
{
int copy = n;
int dgt;
int sum=0,det=0;//determinant
while (copy!=0)
{
dgt=copy%10;
copy=copy/10;
sum+=(dgt*dgt*dgt);
}
if (sum==n)
{det=1;}
else
{det=0;}
return det;
}
I have given here the program for finding armstrong number of a three digits number.
The condition for armstrong number is,
Sum of the cubes of its digits must equal to the number itself.
For example, 407 is given as input.
4 * 4 * 4 + 0 * 0 * 0 + 7 * 7 * 7 = 407 is an armstrong number.
#include <stdio.h>
int main()
{
int i, a, b, c, d;
printf("List of Armstrong Numbers between (100 - 999):\n");
for(i = 100; i <= 999; i++)
{
a = i / 100;
b = (i - a * 100) / 10;
c = (i - a * 100 - b * 10);
d = a*a*a + b*b*b + c*c*c;
if(i == d)
{
printf("%d\n", i);
}
}
return 0;
}
List of Armstrong Numbers between (100 - 999):
153
370
371
407
Reference: http://www.softwareandfinance.com/Turbo_C/Find_Armstrong_Number.html
The program runs but it also spews out some other stuff and I am not too sure why. The very first output is correct but from there I am not sure what happens. Here is my code:
#include <iostream>
using namespace std;
const int MAX = 10;
int sum(int arrayNum[], int n)
{
int total = 0;
if (n <= 0)
return 0;
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0)
total += arrayNum[i];
}
cout << "Sum of odd integers in the array: " << total << endl;
return arrayNum[0] + sum(arrayNum+1,n-1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
sum(x,MAX);
system("pause");
return 0;
}
The term recursion means (in the simplest variation) solving a problem by reducing it to a simpler version of the same problem until becomes trivial. In your example...
To compute the num of the odd values in an array of n elements we have these cases:
the array is empty: the result is trivially 0
the first element is even: the result will be the sum of odd elements of the rest of the array
the first element is odd: the result will be this element added to the sum of odd elements of the rest of the array
In this problem the trivial case is computing the result for an empty array and the simpler version of the problem is working on a smaller array. It is important to understand that the simpler version must be "closer" to a trivial case for recursion to work.
Once the algorithm is clear translation to code is simple:
// Returns the sums of all odd numbers in
// the sequence of n elements pointed by p
int oddSum(int *p, int n) {
if (n == 0) {
// case 1
return 0;
} else if (p[0] % 2 == 0) {
// case 2
return oddSum(p + 1, n - 1);
} else {
// case 3
return p[0] + oddSum(p + 1, n - 1);
}
}
Recursion is a powerful tool to know and you should try to understand this example until it's 100% clear how it works. Try starting rewriting it from scratch (I'm not saying you should memorize it, just try rewriting it once you read and you think you understood the solution) and then try to solve small variations of this problem.
No amount of reading can compensate for writing code.
You are passing updated n to recursive function as argument but not using it inside.
change MAX to n in this statement
for(int i = 0; i < n; i ++)
so this doesnt really answer your question but it should help.
So, your code is not really recursive. If we run through your function
int total = 0; //Start a tally, good.
if (n <= 0)
return 0; //Check that we are not violating the array, good.
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0) //THIS PART IS WIERD
total += arrayNum[i];
}
And the reason it is wierd is because you are solving the problem right there. That for loop will run through the list and add all the odd numbers up anyway.
What you are doing by recursing could be to do this:
What is the sum of odd numbers in:
13,14,8,7,45,89,22,18,6,10
+
14,8,7,45,89,22,18,6
+
8,7,45,89,22,18
+
7,45,89,22 ... etc
And if so then you only need to change:
for(int i = 0; i < MAX; i ++)
to
for(int i = 0; i < n; i ++)
But otherwise you really need to rethink your approach to this problem.
It's not recursion if you use a loop.
It's also generally a good idea to separate computation and output.
int sum(int arrayNum[], int n)
{
if (n <= 0) // Base case: the sum of an empty array is 0.
return 0;
// Recursive case: If the first number is odd, add it to the sum of the rest of the array.
// Otherwise just return the sum of the rest of the array.
if(arrayNum[0] % 2 != 0)
return arrayNum[0] + sum(arrayNum + 1, n - 1);
else
return sum(arrayNum + 1, n - 1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
cout << sum(x,MAX);
}
I tried sieve of Eratosthenes: Following is my code:
void prime_eratos(int N) {
int root = (int)sqrt((double)N);
bool *A = new bool[N + 1];
memset(A, 0, sizeof(bool) * (N + 1));
for (int m = 2; m <= root; m++) {
if (!A[m]) {
printf("%d ",m);
for (int k = m * m; k <= N; k += m)
A[k] = true;
}
}
for (int m = root; m <= N; m++)
if (!A[m])
printf("%d ",m);
delete [] A;
}
int main(){
prime_eratos(179426549);
return 0;
}
It took time : real 7.340s in my system.
I also tried Sieve of Atkins(studied somewhere faster than
sieve of Eratosthenes).
But in my case,it took time : real 10.433s .
Here is the code:
int main(){
int limit=179426549;
int x,y,i,n,k,m;
bool *is_prime = new bool[179426550];
memset(is_prime, 0, sizeof(bool) * 179426550);
/*for(i=5;i<=limit;i++){
is_prime[i]=false;
}*/
int N=sqrt(limit);
for(x=1;x<=N;x++){
for(y=1;y<=N;y++){
n=(4*x*x) + (y*y);
if((n<=limit) &&(n%12 == 1 || n%12==5))
is_prime[n]^=true;
n=(3*x*x) + (y*y);
if((n<=limit) && (n%12 == 7))
is_prime[n]^=true;
n=(3*x*x) - (y*y);
if((x>y) && (n<=limit) && (n%12 == 11))
is_prime[n]^=true;
}
}
for(n=5;n<=N;n++){
if(is_prime[n]){
m=n*n;
for(k=m;k<=limit;k+=m)
is_prime[k]=false;
}
}
printf("2 3 ");
for(n=5;n<=limit;n++){
if(is_prime[n])
printf("%d ",n);
}
delete []is_prime;
return 0;
}
Now,I wonder,none is able to output 1 million primes in 1 sec.
One approach could be:
I store the values in Array but the program size is limited.
Could someone suggest me some way to get first 1 million primes in less
than a sec satisfying the constraints(discussed above) ?
Thanx !!
Try
int main()
{
std::ifstream primes("Filecontaining1MillionPrimes.txt");
std::cout << primes.rdbuf();
}
You've counted the primes incorrectly. The millionth prime is 15485863, which is a lot smaller than you suggest.
You can speed your program and save space by eliminating even numbers from your sieve.
The fastest way I know to check if a number is prime is to check for compositeness, I've implemented the http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test with great sucess for RSA, it is probabilistic, with high degree of success depending on how many times you run it.
Step 1. don't do a printf
Step 2. buy a faster computer.