Print a random number from my own array - c

I've been trying to understand how to print out some random numbers from my own array, dont confuse this with that i want to generate random numbers into an array, which is not what im trying to accomplish.
However, my code is like this
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int myarray[] = { 2, 5, 10 };
//Its here where i dont know how to use rand() in to make the program generate one random number from my array, either 2, 5 or 10. I've tried, but failed.
return 0;
}
Ive not found any similar question to this either, so would greatly appreciate some help.

int number = myarray[rand() % 3];
This generates a random number : 0 1 2 and then accesses that element from the array.

You can use the following formula to generate a random number within a range:
rnd(min, max) = (rand() % (max - min)) + min;
In your case you, min = 0 and max = 3, which gives you rand() % 3.

The other answers use rand() % 3 for generating a (pseudo-)"random" number between 0 and 2 (including both). This might work for you, but is not really random, since the numbers returned by rand() between RAND_MIN and RAND_MAX are not distributed uniformly in terms of their divisibility through a given number n (because the equivalence classes of the modulo relation have unequal amounts of members if RAND_MAX is not a multiple of n).
A better algorithm for getting (pseudo-)random numbers in a given range is:
int RangeRandom(int min, int max) {
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do
{
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % n;
}
You can then use the function RangeRandom as follows:
int myArray[] = { 0, 3, 5 };
printf("%d", myArray[RangeRandom(0, 2)]);

Related

How can I find the largest number in an array that is less than or equal to a random integer?

I am working on an assignment and I'm asked to create an array of fibonacci numbers in a range of 0 to 50,000. Once this array has been initialized I am suppose to create a random number between 2 and 10,000. Then, I'm suppose to compare the members of the fibonacci array with the random number to find the greatest fibonacci number that is less than or equal to the random number.
This is the code that I have so far, it correctly creates the array of fibonacci numbers and the random number. How would I start with comparing the members of the array to the random number?
#include <stdio.h>
#include <string.h>
#include <time.h>
void Get_Fibonacci(int n)
{
int fibArray[25];
int lower = 2, upper = 10000, count = 1;
int i, FibRange = 50000;
int first = 0, second = 1, next = 1;
printf("%d %d", first, second);
//Create fibonacci sequence between 0 and 50,000 and store in array
for (i = 2; (first + second) < FibRange; i++)
{
next = first + second;
fibArray[i] = next;
printf(" %d\n", fibArray[i]);
first = second;
second = next;
}
//Create Random Number between 2 and 10,000
srand(time(0));
int k;
for (k = 0; k < count; k++)
{
n = (rand() % upper - lower + 1) + lower;
}
}
I did a little tweaking to your algorithm. This should do what you are asking.
Basically since the Fibonacci sequence combines of sorted numbers, you can do binary search. Also, in your implementation, your array doesn't have to be of size 25 since you are only holding 23 integers. 0 and 1 are saved in independent variables. In addition, your random number generator was wrong.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_N 10000
#define MIN_N 2
void Get_Fibonacci()
{
int fibArray[25];
int lower = 2, upper = 10000, count = 1, middle = 0,found=0;
int low=0,high=0;
int i, FibRange = 50000,n;
int first = 0, second = 1;
printf("\n\t Fibonacci sequence:\n");
fibArray[0]=0;
fibArray[1]=1;
printf("%d\n%d\n",fibArray[0],fibArray[1]);
/* Creates a fibonacci sequence between 0 and 50,000 and store in an array */
for (i=2; (first+second)<FibRange; i++)
{
fibArray[i]=first+second;
first=second;
second=fibArray[i];
printf("%d\n",fibArray[i]);
}
high=i-1 /* Using the for loop exit condition, as chux suggested */
/* Generates a random number between 2 and 10,000 */
srand(time(0));
n = rand()%(MAX_N+1-MIN_N)+MIN_N;
/* Binary search algorithm */
while (low<=high&&!found)
{
middle=(low+high)/2;
if (n==fibArray[middle])
{
count=fibArray[middle];
found=1; /* To terminate the loop if we have an exact match */
}
else if (n<fibArray[middle])
{
high=middle-1;
}
else
{
low=middle+1;
count=fibArray[middle]; /* Saving the number less than key value */
}
}
printf("\n\tRandom number was: %d\n",n);
printf("\n\tClosest match was: %d\n",count);
return;
}
int main(void)
{
Get_Fibonacci();
return 0;
}
First, need to claify somethings:
1) the for loop for creating a random number is useless since count is always is one
2) n should not be a parameter for the function since you generate a random number in the function
3) the i should start from 0, starting from 2 doesn't make any sense to me. You’re just wasting the first two elements in the array
Largest is the variable that carries the value of the largest element and still smaller than n.
int Largest = fibArray[0];
for(int counter=1; counter<25; counter++){
if(fibArray[counter]>Largest && fibArray[counter]<n)
Largest = fibArray[counter];
}
return Largest;
Lambda expression makes these sort of things significantly easier. I suggest learning about lambda and delegates to help with problems like this in the future

How can I make this very small C program faster?

Is there any simple way to make this small program faster? I've made it for an assignment, and it's correct but too slow. The aim of the program is to print the nth pair of primes where the difference between the two is two, given n.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool isPrime(int number) {
for (int i = 3; i <= number/2; i += 2) {
if (!(number%i)) {
return 0;
}
}
return 1;
}
int findNumber(int n) {
int prevPrime, currentNumber = 3;
for (int i = 0; i < n; i++) {
do {
prevPrime = currentNumber;
do {
currentNumber+=2;
} while (!isPrime(currentNumber));
} while (!(currentNumber - 2 == prevPrime));
}
return currentNumber;
}
int main(int argc, char *argv[]) {
int numberin, numberout;
scanf ("%d", &numberin);
numberout = findNumber(numberin);
printf("%d %d\n", numberout - 2, numberout);
return 0;
}
I considered using some kind of array or list that would contain all primes found up until the current number and divide each number by this list instead of all numbers, but we haven't really covered these different data structures yet so I feel I should be able to solve this problem without. I'm just starting with C, but I have some experience in Python and Java.
To find pairs of primes which differ by 2, you only need to find one prime and then add 2 and test if it is also prime.
if (isPrime(x) && isPrime(x+2)) { /* found pair */ }
To find primes the best algorithm is the Sieve of Eratosthenes. You need to build a lookup table up to (N) where N is the maximum number that you can get. You can use the Sieve to get in O(1) if a number is prime. While building the Sieve you can build a list of sorted primes.
If your N is big you can also profit from the fact that a number P is prime iif it doesn't have any prime factors <= SQRT(P) (because if it has a factor > SQRT(N) then it should also have one < SQRT(N)). You can build a Sieve of Eratosthenes with size SQRT(N) to get a list of primes and then test if any of those prime divides P. If none divides P, P is prime.
With this approach you can test numbers up to 1 billion or so relatively fast and with little memory.
Here is an improvement to speed up the loop in isPrime:
bool isPrime(int number) {
for (int i = 3; i * i <= number; i += 2) { // Changed the loop condition
if (!(number%i)) {
return 0;
}
}
return 1;
}
You are calling isPrime more often than necessary. You wrote
currentNummber = 3;
/* ... */
do {
currentNumber+=2;
} while (!isPrime(currentNumber));
...which means that isPrime is called for every odd number. However, when you identified that e.g. 5 is prime, you can already tell that 10, 15, 20 etc. are not going to be prime, so you don't need to test them.
This approach of 'crossing-out' multiples of primes is done when using a sieve filter, see e.g. Sieve of Eratosthenes algorithm in C for an implementation of a sieve filter for primes in C.
Avoid testing ever 3rd candidate
Pairs of primes a, a+2 may only be found a = 6*n + 5. (except pair 3,5).
Why?
a + 0 = 6*n + 5 Maybe a prime
a + 2 = 6*n + 7 Maybe a prime
a + 4 = 6*n + 9 Not a prime when more than 3 as 6*n + 9 is a multiple of 3
So rather than test ever other integer with + 2, test with
a = 5;
loop {
if (isPrime(a) && isPrime(a+2)) PairCount++;
a += 6;
}
Improve loop exit test
Many processors/compilers, when calculating the remainder, will also have available, for nearly "free" CPU time cost, the quotient. YMMV. Use the quotient rather than i <= number/2 or i*i <= number to limit the test loop.
Use of sqrt() has a number of problems: range of double vs. int, exactness, conversion to/from integer. Recommend avoid sqrt() for this task.
Use unsigned for additional range.
bool isPrime(unsigned x) {
// With OP's selective use, the following line is not needed.
// Yet needed for a general purpose `isPrime()`
if (x%2 == 0) return x == 2;
if (x <= 3) return x == 3;
unsigned p = 1;
unsigned quotient, remainder;
do {
p += 2;
remainder = x%p;
if (remainder == 0) return false;
quotient = x/p; // quotient for "free"
} while (p < quotient); // Low cost compare
return true;
}

Array of random numbers using C program

Im new to C program and I am required create 100 random numbers between 50 and 70, and store them in an array of double. How do I start?
Create an array:
int my_array[100];
Seed the random number generator
srand(0);
Loop over your array and fill it up!:
int i;
for (i = 0; i < 100; i++) {
my_array[i] = rand();
}
That's a start. However, the range of rand() is much larger than the range of random numbers you want. There are many ways to narrow the range. If you don't care about the numbers being perfectly random, you can use the modulo operator, where 13 % 10 = 3.
This is for ints. I want to leave some fun for the reader.
If the number is between 50 and 70, then I would say, try modulo and the rand() function of c.
So firstly since you will want yo use random numbers, I would advice including the standard library.
Do:
#include <stdlib.h>`
double bal[100];
for (int f = 0; f < 100 ;f++) {
bal[f] = (rand() % 20) + 50;
}
The reason why I modulo 20 is because the difference between 50 and 70 is 20 so, if you assume 50 is zero then 70 will be 20 and so any number we will produce will be between these numbers. Hope it helps! */
you can use this to range the rand function:
rand() % (max_number + 1 - minimum_number) + minimum_number
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random_numbers(int *array, int len, int min, int max){
for (int i = 0; i < len; i++)
array[i] = rand() % (max - min + 1) + min;
}
int main() {
system("cls");
srand(time(0));
int numbers[100] = {};
gen_random_numbers(numbers, 100, 50, 70);
return 0;
}

random() function only spitting out big numbers

I am using the random() function, and I was wondering if there is a reason that I'm always getting 8-10 digit numbers. I just want to make sure there isn't something wrong with my program. Thanks.
Here's the function:
void random_array(int* p, int size) {
/*seed random number generator */
srandom(time(NULL));
int i;
for(i = 0; i < size; i++)
*(p+i) = random();
}
Well, mathematically the chance that you will get a big number is a lot more than the chance for a (relatively) small one. For instance, if you pick a random number with (1-4) digits, the chance that it would be in the range (0-99) would be only 1 %.
With that said, if you want smaller numbers, you can take the random modulo some certain number:
a = random() % 100; // this will give you a random number from 0 to 99
b = 10 + random() % 15; // random number from 10 to 24
Number of 8-10 digits numbers: 10,000,000,000 - 100,000,000 = 9,900,000,000 (9.9 billion)
Number of 0-7 digit numbers: 10,000,000 (10 million)
In other words, there are 990 8-10 digit numbers for every 1 0-7 digit number. Therefore, you can expect to get about 1 0-7 digit number for every 990 8-10 digit numbers.
Put simply, it's because there are more of them.
How large a number were you expecting to receive from random()?
If you want to limit the size of the number generated, simply use a modulus operator to limit the result to the remainder (in the example below a number from 0 to 999):
*(p+i) = random() % 1000;
Mathematically it is likely since big numbers are..well.. more than small ones, so yes. It is much more likely to get such a number.
To generate a custom-interval random number use something like
http://ideone.com/bWbBgJ
#include <stdlib.h>
#include <stdio.h>
// Generate random numbers in the min-max interval
void random_array(int* p, int size, int min, int max) {
/*seed random number generator */
srandom(time(NULL));
int i;
for(i = 0; i < size; i++)
*(p+i) = (random() % max) + min;
}
int main(void) {
int array[3];
random_array(array, 3, 0, 12);
printf("%d\n", array[0]);
printf("%d\n", array[1]);
printf("%d\n", array[2]);
return 0;
}

What is Sum of Even Terms In Fibonacci (<4million)? [Large Value Datatype Confusion]

By starting with 1 and 2, the first 10 terms of Fibonacci Series will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed 4 million.
Now, I got the idea for how to do this. But I'm confused about the data types to hold such big data. I'm getting weird results with int. :(
MORE: Its Project Euler 2nd question. But I can't get it. I get crazy values as answer. Can someone please post the ideal program?
EDIT: Here's what I wrote for just printing Fibonacci to screen. Bare Basic. My variable goes crazy even when I give 100 for the limit. Is my code wrong?
// Simple Program to print Fibonacci series in Console
#include <stdio.h>
int main() {
int x=1,y=2,sum=0,limit=0,i=0,temp=0;
printf("Enter Limit:");
scanf("%d",&limit);
if(limit==1)
printf("%d",x);
else if(limit>1) {
printf("%d %d",x,y);
if (limit>2) {
while (i<limit-2) {
temp=y;
sum=x+y;
x=temp;
y=sum;
printf(" %d",sum);
i++;
}
}
}
printf("\n");
return 0;
}
SOLVED: Actually, I managed to get the solution myself. Here's my program. It works.
#include <stdio.h>
int main() {
int x=1,y=2,sum,limit; //Here value of first 2 terms have been initialized as 1 and 2
int evensum=2; //Since in calculation, we omit 2 which is an even number
printf("Enter Limit: "); //Enter limit as 4000000 (4million) to get desired result
scanf("%d",&limit);
while( (x+y)<limit ) {
sum=x+y;
x=y;
y=sum;
if (sum%2==0)
evensum+=sum;
}
printf("%d \n",evensum);
return 0;
}
Since you only want up to four million, it's likely that int is not your problem.
It's quite possible that your program is buggy and that the data storage is just fine, so you should test your program on smaller values. For example, it's clear that the sum of the first three even terms is 44 (hint: every third term is even) so if you run your program with a cap of 50, then you should instantly get 44 back. Keep running small test cases to get confidence in the larger ones.
For security, use the 'long' data type; the C standard requires that to hold at least 4 billion, but on most machines, 'int' will also hold 4 billion.
enum { MAX_VALUE = 4000000 };
int sum = 0;
int f_n0 = 0;
int f_n1 = 1;
int f_n2;
while ((f_n2 = f_n0 + f_n1) < MAX_VALUE)
{
if (f_n2 % 2 == 0)
sum += f_n2;
f_n0 = f_n1;
f_n1 = f_n2;
}
printf("%d\n", sum);
I am not a programmer, but here's an adaptation to Leffler's code without the IF-criterion. It should work for MAX_VALUES above 2 (given there are no mistakes in programming syntax), based on a pattern I found in the even-only fibonacci series: 0,2,8,34,144,610,2584... so interestingly: f_n2 = 4*f_n1 + f_n0. This also means this program only needs 1/3rd of the calculations, since it doesn't even consider/calculate the odd fibonacci numbers.
enum { MAX_VALUE = 4000000 };
int sum = 2;
int f_n0 = 0;
int f_n1 = 2;
int f_n2 = 8;
while (f_n2 < MAX_VALUE)
{
sum += f_n2;
f_n0 = f_n1;
f_n1 = f_n2;
f_n2 = 4*f_n1 + f_n0;
}
printf("%d\n", sum);
Try changing this:
while (i<limit-2)
to this:
while (y<limit)
As written, your program is cycling until it gets to the 4 millionth Fibonacci number (i.e. when i gets to 4 million, though overflow obviously happens first). The loop should check to see when y (the larger Fibonacci number) becomes greater than 4 million.
Guys, I got the answer. I confirmed the result and int can handle it. Here's my program:
#include <stdio.h>
int main() {
int x=1,y=2,sum,limit; //Here value of first 2 terms have been initialized as 1 and 2
int evensum=2; //Since in calculation, we omit 2 which is an even number
printf("Enter Limit: "); //Enter limit as 4000000 (4million) to get desired result
scanf("%d",&limit);
while( (x+y)<limit ) {
sum=x+y;
x=y;
y=sum;
if (sum%2==0)
evensum+=sum;
}
printf("%d \n",evensum);
return 0;
}
Thx for all the replies and help. "Thinking on my feet" to the rescue :)
An amusing solution is to use the closed form for Fibonacci sequences and the closed form for geometric progressions. The end solution looks like this:
sum = ( (1-pow(phi_cb, N+1)) / (1-phi_cb) - (1-pow(onephi_cb,N+1)) / (1-onephi_cb)) / sqrt(5);
where
double phi = 0.5 + 0.5 * sqrt(5);
double phi_cb = pow(phi, 3.0);
double onephi_cb = pow(1.0 - phi, 3.0);
unsigned N = floor( log(4000000.0 * sqrt(5) + 0.5) / log(phi) );
N = N / 3;
with all the caveats regarding double to int-type conversions of course.
int is big enough for values in the millions on almost every modern system, but you can use long if you are worried about it. If that still gives you weird results, then the problem is with your algorithm.
Use BigInt.
Then again, unsigned int stores values up to over 4 billion, so you shouldn't be having any problems even with "sum of all fibonacci numbers up to 4 million" (which, obviously, has to be less than 8 mil)?
Your program prints F_1 + ..+ F_limit and not F_1 + ... F_n with F_n < limit as you described.
Check the Wikipedia article on Fibonacci Numbers and Sloane A000045: Fibonacci numbers grows exponentially. Checking this table F_48 = 4807526976 which exceeds int. F_100 is 354224848179261915075 which surely overflows even int64_t (your stack doesn't, though).
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
int main()
{
long first = 1, second = 2, next, c;
int sum=0;
for ( c = 1 ; c <100000000; c++ )
{
next = first + second;
if(next>=4000000)
{
next= next-second;
break;
}
first = second;
second = next;
if(next%2==0){
sum=sum+next;
}
}
printf("the sum of even valued term is %d\n",sum+2);
}
Here's my program:
#include <iostream>
long int even_sum_fibonacci(int n){
int i = 8;
int previous_i = 2;
int next_i = 0;
long int sum = previous_i + i;;
while(n>next_i){
next_i = i*4 + previous_i;
previous_i = i;
i = next_i;
sum = sum + i;
}
return sum - next_i; //now next_i and i are both the bigger number which
//exceeds 4 million, but we counted next_i into sum
//so we'll need to substract it from sum
}
int main()
{
std::cout << even_sum_fibonacci(4000000) << std::endl;
return 0;
}
Because if you look at the fibonacci series (at the first few even numbers)
2 8 34 144 610 2584 ... you'll see that it matches the pattern that
next_number = current_number * 4 + previous_number.
This is one of solutions. So the result is 4613732
You can try the below code.
public static void SumOfEvenFibonacciNumbers()
{
int range = 4000000;
long sum = 0;
long current = 1;
long prev = 0;
long evenValueSum= 0;
while (evenValueSum< range)
{
sum = prev + current;
prev = current;
current = sum;
if (sum % 2 == 0 )
{
evenValueSum = evenValueSum+ sum;
}
}
Console.WriteLine(evenValueSum);
}
You can use the above code.
import numpy as np
M = [[0,1],[1,1]]
F = [[0],[1]]
s = 0
while(F[1][0] < 4000000):
F = np.matmul(M, F)
if not F[0][0]%2:
s+=F[0][0]
print(s)
We can do better than this in O(log n) time. Moreover, a 2 × 2 matrix and a two dimensional vector can be multiplied again in O(1) time. Therefore it suffices to compute Mn.
The following recursive algorithm computes Mn
If n = 0, return I2
If n = 1, return M.
If n = 2m.
Recursively compute N = Mm, and set P = N2.
If n = 2m+1, set P = PM.
Return P.
We have T(n) = T(n/2) + O(1), and by master's theorem T(n) = O(log n)
You can also use recurrence for Even Fibonacci sequence is:
EFn = 4EFn-1 + EFn-2
with seed values
EF0 = 0 and EF1 = 2.
SIMPLE SOLUTION WOULD BE:-
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n1=1;
int n2=2;
int num=0,sum;
for (int i=1;i,n1<4000000;i++)
{
cout<<" "<<n1;
num=n1+n2;
if(!(n1%2))
{
sum+=n1;
}
n1=n2;
n2=num;
}
cout<<"\n Sum of even term is = "<<sum;
return 0;
}
Here's my offer, written in Java. I had been using a for loop whose exit value was 4000000 but realized early on there was a serious overflow for the sum of the numbers. Realizing the Fibonacci Number has to be less than 4 million (and not the sum), I changed to a while loop and got it:
class Main {
public static void main(String[] args) {
int counter = 0;
int fibonacciSum = 0, fibonacciNum = 0;
int previous = 1, secondPrevious = 0;
fibonacciNum = previous + secondPrevious;
while (fibonacciNum <= 4000000){
if (fibonacciNum % 2 == 0 ){
counter++;
fibonacciSum += fibonacciNum;
secondPrevious = previous;
previous = fibonacciNum;
}//ends if statement
else {
secondPrevious = previous;
previous = fibonacciNum;
}//ends else statement
fibonacciNum = previous + secondPrevious;//updates number
}//ends loop
System.out.println("\n\n\n" + fibonacciSum);
}//ends main method
}//ends Main

Resources