When I am trying to generate a random number 0 through int:
//Populate Currently Allocated Reasource for each customer
for (i = 0; i < NUMBER_OF_CUSTOMERS; i++)
{
printf("%d:[ ",i);
for (j = 0; j < NUMBER_OF_RESOURCES; j++)
{
allocation[i][j] = rand() % maximum[i][j];
printf("%d ",allocation[i][j]);
}
printf("] \n\n");
}
I get a floating point exception when maximum[i][j] is 0.
Are there any better means of creating a random number without the floating point error caused by rand() % 0?
EDIT:
When maximum is 0, the random number output should just be 0.
Taking a % b gives you the remainder when a is divided by b. As such, it will always give you a result that is less than b, and it doesn't work when b is zero, because you can't divide by zero.
If you want a random number between 0 and x, you need to take rand() % (x + 1).
Try to use this instead
//Populate Currently Allocated Reasource for each customer
for (i = 0; i < NUMBER_OF_CUSTOMERS; i++)
{
printf("%d:[ ",i);
for (j = 0; j < NUMBER_OF_RESOURCES; j++)
{
allocation[i][j] = maximum[i][j] ? (rand() % maximum[i][j]) : 0;
printf("%d ",allocation[i][j]);
}
printf("] \n\n");
}
You said:
When maximum is 0, the random number output should just be 0.
You can add a check to take care of this.
if ( maximum[i][j] == 0 )
{
allocation[i][j] = 0;
}
else
{
allocation[i][j] = rand() % maximum[i][j];
}
You can use the ?: operator to write that extra condition neatly:
allocation[i][j] = maximum[i][j] ? (rand() % maximum[i][j]) : 0;
?: Conditional Expression: If Condition is true ? Then value X : Otherwise value Y
In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.
Wikipedia
When maximum is 0, the random number output should just be 0.
The modulo operator is the remainder after a division. Since division by zero is undefined, so is modulo 0.
You need a condition to prevent attempting to divide by zero. You can do that with if/else statements, or the ternary operator (?:). In other words, change this
allocation[i][j] = rand() % maximum[i][j];
to one of the following.
if (maximum[i][j] == 0)
{
allocation[i][j] = 0;
}
else
{
allocation[i][j] = (rand() % maximum[i][j]);
}
or
allocation[i][j] = (maximum[i][j] == 0) ? (rand() % maximum[i][j]) : 0;
Related
I'm a first year student in a programming university and my first assignment is to find the sum of prime numbers between 3990000000 and 4010000000. The problem is everything I do, when I run the program it says the sum is 0 with a return value of 25. I've been trying to debug this code but with no luck, could someone help me?
My code is:
#include <stdio.h>
#define STARTNUMBER 3990000000
#define ENDNUMBER 4010000000
int main() {
unsigned int num;
int j, c, flag, sum = 0;
flag = 1;
c = 5;
j = 7;
for (num = STARTNUMBER; num <= ENDNUMBER; num++) {
if (num % 2 == 0) { /*if number mod 2 equals zero go to next number*/
flag = 0;
break;
}
if (num % 3 == 0) { /*if number mod 3 equals zero go to next number*/
flag = 0;
break;
} else
/*check if number is prime with the sequences 5+6+6...<=sqrt(number) and 7+6+6..<=sqrt(number)*/
while (c * c <= num && j * j <= num && flag == 1) {
if (num % c == 0 || num % j == 0) {
flag = 0;
break;
}
c += 6;
j += 6;
}
if (flag == 1)
sum++;
}
printf("There are %d prime numbers", sum);
}
You are asking for the sum of the prime number, even if your code is just printing how many they are. Assuming you've misunderstood the exercise, I try to show a possible problem of your original question, glimpsing a possible trick in your exercise since the interval is very close to 232.
Assuming also you are on a 64-bit environment, if there are at least two prime numbers in that inteval, the sum is going to be greater than INT_MAX (231 - 1). An int is not sufficient to store a value, and also unsigned int is not sufficient since UINT_MAX is 232 - 1.
Finally, assuming you've solved your problems with the break statements already described in the comments, try to store your sum variable into a unsigned long int, and replace the last part of the loop with
if (flag==1)
sum += num;
Ok, so I enjoy using SPOJ to practice programming and developing algorithms. I always have issues with the questions though. A lot of times, I will get a "wrong answer" message when clearly my code answers the questions properly. If someone could tell me if there is anything wrong or why SPOJ would be telling me my answer was wrong that would be awesome! Here is the problem word-for-word:
Prime Number Generator
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
My code:
int n;
scanf("%d", &n);
if(n > 10){ return 0; }
n = n*2;
int arr[n];
for(int i = 0; i < n; i++){ scanf("%d", &arr[i]); }
for(int i = 0; i < n; i += 2){
if(arr[i] >= 1 && arr[i] <= arr[i+1] && arr[i+1] <= 1000000000 && arr[i+1]-arr[i] <= 100000){
for(int j = arr[i]; j <= arr[i+1]; j++){
if(j % 2 == 1 || j == 2){
printf("%d\n", j);
}
}
printf("\n");
}
}
return 0;
INPUT:
2
7 11
2 9
OUTPUT:
7
9
11
2
3
5
7
9
A lot of times, I will get a "wrong answer" message when clearly my code answers the questions properly.
This is not one of those cases as evidenced by the fact that, despite the contrary, your code seems to think that 9 is a prime. The line:
if(j % 2 == 1 || j == 2)
combined with the fact that you appear to be printing all odd numbers (and two), is an indication that your prime check is incorrect.
Where you should probably start is with a simple prime check function such as:
int isPrime(int num) {
int chk = 2;
while (chk * chk <= num)
if ((num % chk) == 0)
return 0;
++chk;
}
return 1;
}
Once you have it working, then worry about performance (two of my favourite mantras are "Wrong is the least optimised state" and "Get it working first, then get it working fast").
The things you can look into for optimisations include, but are not limited to:
Eratosthenes sieve where, provided the range of primes isn't too large, it can greatly improve speed by not having to do a lot of calculations for each prime test; and
Using the fact that all primes other than two and three are of the form 6n±1, effectively tripling the speed of the isPrime function (see here for an explanation).
For that second bullet point, you can use:
int isPrime(unsigned int num) {
// Special cases for 0-3.
if (num < 2) return 0;
if (num < 4) return 1;
int chk = 5, add = 2; // prime generator, 6n +/- 1.
while (chk * chk <= num) // check every candidate.
if ((num % chk) == 0) // check if composite.
return 0;
chk += add; // next candidate.
add = 6 - add; // alternate +2, +4.
}
return 1; // no factors, must be prime.
}
Is there a simpler way of generating sparse matrix other than this?
for (i = 0; i < 1000; i++)
{
if (rand() % 3 == 0)
{
array[i] = rand() % 3;
}
else
{
array[i] = ((rand() % 3) - 1);
}
}
Thanks.
I used array for presentational purposes
With a determine how sparse you want it to be.
for (i = 0; i < 1000; i++)
{
if (rand() % a == 0)
{
array[i] = rand() % 100;
}
else
{
array[i] = 0;
}
}
Let t be the target number of non-zero elements in the array, which should be much less than the length of the array for sparseness. I'm assuming your array is of length length. I'm also generating the random indices without the modulus operator to avoid modulo bias.
for (i = 0; i < t; ++i) {
int index = (int) (length * ((double) rand() / (RAND_MAX + 1.0)));
array[index] = i % 2 ? -1 : 1;
}
Note that this may give a few less than t non-zero elements because random numbers can produce duplicates, but that should be rare if it really is sparse, e.g., t < square root of the array length. If you're worried about duplicate randoms making things sparser than you want, you can modify accordingly:
for (i = 0; i < t;) {
int index = (int) (length * ((double) rand() / (RAND_MAX + 1.0)));
if (array[index]) { /* something already at this index */
continue; /* skip incrementing and try again */
}
array[index] = i % 2 ? -1 : 1;
++i;
}
In both cases I'm alternating +/- ones for the non-zero values, but if you want it more random that would be easy to replace the right-hand side of the assignment of array[index].
Finally, I ask your indulgence if I fluffed something on C syntax. My C is about 15 years rusty, but the intent should be clear.
for (i = 0; i < n; i++)
{
x[i] = (float) (i * step);
k = 5;
sum = 0;
while(k > 0)
{
sum = sum + (1/k) * sin((k*PI*x[i])/5);
k = k - 2;
}
y1[i] = (4/PI)*sum;
y2[i] = 0*(4/PI)*sin((PI*x[i])/5);
}
When debugging for each value of k other than 1 the sum shows as being equal to 0, am I implementing the loop correctly?
EDIT 1:
int k;
double sum;
Since both 1 and k are ints -- 1/k is integer division, its always going to be 0 if k > 1. Therefore nothing is added to sum. You want 1/k to perform floating point division. Try 1.0 / k instead of 1/k.
1/k will give 0. Since it is Integer Division.
You will have to give 1.0/k or 1/(float)k
I am trying to generate all the prime factors of a number n. When I give it the number 126 it gives me 2, 3 and 7 but when I give it say 8 it gives me 2, 4 and 8. Any ideas as to what I am doing wrong?
int findPrime(unsigned long n)
{
int testDivisor, i;
i = 0;
testDivisor = 2;
while (testDivisor < n + 1)
{
if ((testDivisor * testDivisor) > n)
{
//If the test divisor squared is greater than the current n, then
//the current n is either 1 or prime. Save it if prime and return
}
if (((n % testDivisor) == 0))
{
prime[i] = testDivisor;
if (DEBUG == 1) printf("prime[%d] = %d\n", i, prime[i]);
i++;
n = n / testDivisor;
}
testDivisor++;
}
return i;
}
You are incrementing testDivisor even when you were able to divide n by it. Only increase it when it is not divisible anymore. This will result in 2,2,2, so you have to modify it a bit further so you do not store duplicates, but since this is a homework assignment I think you should figure that one out yourself :)
Is this based on an algorithm your professor told you to implement or is it your own heuristic? In case it helps, some known algorithms for prime factorization are the Quadratic Sieve and the General Number Field Sieve.
Right now, you aren't checking if any divisors you find are prime. As long as n % testDivisor == 0 you are counting testDivisor as a prime factor. Also, you are only dividing through by testDivisor once. You could fix this a number of ways, one of which would be to replace the statement if (((n % testDivisor) == 0)) with while (((n % testDivisor) == 0)).
Fixing this by adding the while loop also ensures that you won't get composite numbers as divisors, as if they still divide n, a smaller prime factor must have also divided n and the while loop for that prime factor wouldn't have left early.
Here is code to find the Prime Factor:
long GetPrimeFactors(long num, long *arrResult)
{
long count = 0;
long arr[MAX_SIZE];
long i = 0;
long idx = 0;
for(i = 2; i <= num; i++)
{
if(IsPrimeNumber(i) == true)
arr[count++] = i;
}
while(1)
{
if(IsPrimeNumber(num) == true)
{
arrResult[idx++] = num;
break;
}
for(i = count - 1; i >= 0; i--)
{
if( (num % arr[i]) == 0)
{
arrResult[idx++] = arr[i];
num = num / arr[i];
break;
}
}
}
return idx;
}
Reference: http://www.softwareandfinance.com/Turbo_C/Prime_Factor.html
You can use the quadratic sieve algorithm, which factors 170-bit integers in second and 220-bit integers in minute. There is a pure C implementation here that does not require GMP or an external library : https://github.com/michel-leonard/C-Quadratic-Sieve, it's able to provide you a list of the prime factors of N. Thank You.