It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What does it do - element at index 'i' is the product of all input elements except for the input element at 'i'.
As an example, if arr = { 1, 2, 3, 4 }, then
output = { 2*3*4, 1*3*4, 1*2*4, 1*2*3 }.
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
int n;
long long int arr[1000]={0},prod=1;
cin>>n;
for(int i=0;i<n;i++){
cin>>arr[i];
prod*=arr[i];
}
if(prod!=0)
for(int i=0;i<n;i++){
cout<<(prod/arr[i])<<endl;
}
else
for(int i=0;i<n;i++){
cout<<"0"<<endl;
}
return 0;
}
The simplest case for which it fails is 2 0 1. The correct result would be 1 0, your result is 0 0.
More generally, it fails if there is exactly one zero and at least one non-zero in the input set.
As was already noted, the problem is when one of the inputs is zero, and you try to divide by zero. To properly compute the products, an algorithm which only performs multiplications and no divisions is needed, such as the following one.
#include <stdio.h>
#include <stddef.h>
// Input: an array of 2^(exp) doubles
// Output: an array of 2^(exp) doubles, where each one is the
// product of all the numbers at different indices in
// the input
// Return value: the product of all inputs
double products (unsigned int exp, const double *in, double *out)
{
if (exp == 0) {
out[0] = 1;
return in[0];
}
size_t half_n = (size_t)1 << (exp - 1);
double prod_left = products(exp - 1, in, out);
double prod_right = products(exp - 1, in + half_n, out + half_n);
for (size_t i = 0; i < half_n; i++) {
out[i] *= prod_right;
out[half_n + i] *= prod_left;
}
return prod_left * prod_right;
}
int main ()
{
double in[8] = {1, 2, 3, 4, 5, 6, 7, 8};
double out[8];
products(3, in, out);
for (size_t i = 0; i < 8; i++) {
printf("%f ", out[i]);
}
printf("\n");
return 0;
}
This requires O(n*log(n)) time and no extra space, except for the O(log(n)) space used by the recursion. While it's nice and easy to understand, it is not optimal; see this question.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I need to convert two integers into two arrays of digits, so for example 544 would become arr[0] = 5, arr[1] = 4, arr[2] = 4.
I have found some algorithms doing this, but they create new array, and return this. I would have to allocate this memory for two arrays, so I wanna pass two integers by reference and do this on them directly.
I guess I can do this, because these integers are in fact template types, so they should be changeable. That's why I added C++ tag here.
Just using something like this:
int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array
while (n) { // loop till there's nothing left
a[i++] = n % 10; // assign the last digit
n /= 10; // "right shift" the number
}
Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of i as well as the increment/decrement based on how you'd like to determine to length of the value.
(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:
{
char *df = a, *dr = a + i - 1;
int j = i >> 1;
while (j--)
{
char di = *df, dj = *dr;
*df++ = dj, *dr-- = di; /* (exchange) */
}
}
A simple solution is:
int i = 12312278;
std::vector<int> digits;
while (i)
{
digits.push_back(i % 10);
i /= 10;
}
std::reverse(digits.begin(), digits.end());
or, string based ( i >= 0 )
for (auto x : to_string(i))
digits.push_back(x-'0');
Call the integer a.
To get the units digit of a, a % 10
To shift a down so the tens is the units digit, a / 10
To know when you're done, a == 0
To know how large your array needs to be in the first place, min(ceil(log(a+1, 10)), 1) (to convince yourself this works, try the logarithm part of it in a calculator. if you don't have multiple argument log, use the identity log(x,y) == log(x)/log(y))
You can do something like this if you are using C++:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int a=544;
stringstream str;
str << a;
string arr;
str>>arr;
for(int i=0; i<arr.length(); i++)
{
cout << arr[i];
}
system("pause");
return 0;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Assume we have a vector A of size N.
Pawn starts at A[0] and jumps to index pointed by A[0]: value of A[0] tells how it has to move, i.e: if index is 6.
A[6]=1 -> move 1 to the right, to A[7]
A[6]=-2 -> move 2 to the left, to A[4]
If pawn gets to the last index and it is positive, the pawn gets out of scope
example:
A 0 | 1 | 1 | 3 | 4 | 5
2 -1 4 1 4 2
Max value that each element contains is 1 000 000 and N < 1 000 000. function should return 4.
TASK: write a function int arrayJmp ( const vector<int> &A )that returns -1 if pawn will never get out of a table or returns number of moves if it will jump out of the array. worst case complexity should be O(n). you can find my answer below. is this right?
Are you using 'table', 'array' and 'vector' interchangeably?
The request is quite simple:
if ((i = array[ index ]) < 0 || i >= sizeof(array)) ;//out of bounds
otherwise i is within bounds
#include <iostream>
#include <vector>
int jump_array(const std::vector<int>& vector)
{
int index = 0;
int old_index = 0;
int size = vector.size();
int count = 0;
do
{
old_index = index;
index += vector[index];
if(count >= size)
{
return -1;
}
else
{
count++;
}
}
while(index < size);
return vector[old_index];
}
int main()
{
std::vector<int> vector;
vector.push_back(2);
vector.push_back(-1);
vector.push_back(4);
vector.push_back(1);
vector.push_back(4);
vector.push_back(2);
std::cout << jump_array(vector);
}
#include <algorithm>
void myfunction (int &i) { // function:
i=1000001;
}
int arrayJmp ( const vector<int> &A ) {
int N=A.size();
vector<int> indexes;
for_each (indexes.begin(), indexes.end(), myfunction);
int index=0;
while(std::find(indexes.begin(), indexes.end(), index) == indexes.end()){
indexes.push_back(index);
index+=A[index];
if (index==(N-1)&&A[index]>0) return indexes.size()+1;
}
return -1;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Here is the link to the problem.
The problem asks the number of solutions to the Diophantine equation of the form 1/x + 1/y = 1/z (where z = n!). Rearranging the given equation clearly tells that the answer is the number of factors of z2.
So the problem boils down to finding the number of factors of n!2 (n factorial squared).
My algorithm is as follows
Make a Boolean look up table for all primes <= n using Sieve of Eratosthenes algorithm.
Iterate over all primes P <= n and find its exponent in n!. I did this using step function formula. Let the exponent be K, then the exponent of P in n!2 will be 2K.
Using step 2 calculate number of factors with the standard formula.
For the worst case input of n = 106, my c code gives answer in 0.056s.
I guess the complexity is no way greater than O(n lg n).
But when I submitted the code on the site, I could pass only 3/15 test cases with the verdict on the rest as time limit exceeded.
I need some hints for optimizing this algorithm.
Code so far:
#include <stdio.h>
#include <string.h>
#define ULL unsigned long long int
#define MAXN 1000010
#define MOD 1000007
int isPrime[MAXN];
ULL solve(int N) {
int i, j, f;
ULL res = 1;
memset(isPrime, 1, MAXN * sizeof(int));
isPrime[0] = isPrime[1] = 0;
for (i = 2; i * i <= N; ++i)
if (isPrime[i])
for (j = i * i; j <= N; j += i)
isPrime[j] = 0;
for (i = 2; i <= N; ++i) {
if (isPrime[i]) {
for (j = i, f = 0; j <= N; j *= i)
f += N / j;
f = ((f << 1) + 1) % MOD;
res = (res * f) % MOD;
}
}
return res % MOD;
}
int main() {
int N;
scanf("%d", &N);
printf("%llu\n", solve(N));
return 0;
}
You have an int overflow here:
for (j = i, f = 0; j <= N; j *= i)
If 46340 < i < 65536 and for many larger i, in the second iteration j will be negative if overflow wraps around (it is undefined behaviour, so anything could happen).
Replace it with e.g.
for(j = N / i, f = 0; j > 0; j /= i) {
f += j;
}
It is, however, unlikely that the extra iterations due to the overflow would cause a "time limit exceeded", that will likely only cause wrong results.
So the generic advice is
Sieve only odd numbers, perhaps also eliminate multiples of 3 from the sieve. Eliminating the odd numbers from the sieve roughly halves the time needed to sieve.
Don't use an entire int for the flags, use bits or at least chars. That gives better cache locality and a further speedup.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have compiled the following program and i know what it does, it takes ten numbers multiplies it my itself and then at the end add their total together.
#include <iostream>
using namespace std;
main()
{
int a[10];//1
int sumOfSquares = 0 ;//2
int i =0; //3`enter code here`
cout << "Please enter the ten numbers one by one " << endl;//4
for (i = 0 ; i < 10 ; i++)//5 dont get what this does,
// obviously its a for loop,
// but why does it increment i by one
{
cin >> a [i];//6 this means store the 10 numbers
// in array a and refer to it by the variable i
}
for (i = 0 ; i < 10 ; i++) //7 again i dont get why this is here
{
sumOfSquares = sumOfSquares + a[i]*a[i];//8
}
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
why does it increment i by one
Array indexes run from 0 to N-1, where N is the number of elements in the array.
i++ increments the value of i by 1 (equivalent to i = i + 1;). Incrementing i in the for loop is a construct for accessing each element of the array a (in order):
for (int i = 0; i < 10; i++)
{
a[i] = 2; /* just example */
}
is equivalent to:
a[0] = 2;
a[1] = 2;
...
a[9] = 2;
As others have commented, get a C++ book (see this SO question for a list of C++ books).
#include <iostream>
using namespace std;
main()
{
//declare space in memory for 10 numbers to be stored sequentially
//this is like having ten variables, a1, a2, a3, a4 but rather than having
//hardcoded names, you can say a[4] or rather i=4, a[i], to get variable a4.
int a[10];
int sumOfSquares = 0 ; //space for a number to be stored called sumOfSquares
int i =0; //space for a number to be stored called i
cout << "Please enter the ten numbers one by one " << endl; //print msg to screen
for (i = 0 ; i < 10 ; i++) //make i = 0; while i < 10 run this code! increase i by 1 each time
{
//a stores 10 numbers. put the number the user entered in space
//a[0] the first time, a[1] the second time, a[2] the third time etc etc.
cin >> a [i];
}
//run this code 10 times, with i=0 the first time, i=1 the second time,
// i=3 the third time etc etc.
for (i = 0 ; i < 10 ; i++)
{
//get the number at a[0] multiple it by the number at a[0]
//add it to value already in sumOfSquares so this number goes up and up and up.
//the second time through the loop get a[1] and multiply it by a[1].
sumOfSquares = sumOfSquares + a[i]*a[i];
}
//print answer to screen
cout << "The sum of squares is "<< sumOfSquares << endl; //9
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
#include <iostream>
using namespace std;
void main()
{
int i = 0;
while (i < 1000)
{
int TEMP = i * 2;
cout << i << endl;
TEMP = i;
i = i +1;
// ???
}
return;
}
I'm so confused?? :(
The Fibonacci sequence F is F(n) = F(n - 1) + F(n - 2), F(0) = 0, F(1) = 1.
Here's some psuedo-code:
Start Counter1 at 0
Start Counter2 at 1.
For i = 0 to 1000
New value = Counter1 + Counter2
Print new value
Counter2 = Counter1
Counter1 = New Value
End For
This doesn't print out 0 or 1; it starts at F(2). You can easily fix this by just printing out 0 and 1 first. Also, this code prints the first 1000 numbers. If you change this to: While Counter1 < 1000, you'll stop when you reach or pass 1000.
It's up to you to implement it, and make sure you understand how it works.
First you should check that you understand the definition of the Fibonacci numbers.
By definition, the first two Fibonacci numbers are 0 and 1, and each remaining number is the sum of the previous two. Some sources omit the initial 0, instead beginning the sequence with two 1s.
You need two variables to remember the state, not just one as you were trying to do. And you don't multiply by two, you just add the two variables.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int j = 1;
while (i < 1000)
{
/* Print a number. */
cout << i << endl;
/* Set j to the sum of i and j, and i to the old value of j. */
int TEMP = j;
j += i;
i = TEMP;
}
return 0;
}
If you would like just a hint, Google "recursion".
If you would like the answer, Google "recursion fibonacci C++", but PLEASE try to work it out with the hint above :) It's worth it.