Peggy
Peggy

Reputation: 49

Generate a random number which fulfills some conditions

I want to generate a random number which shouldn't be greater than variable 'max' and fulfills the condition below:

    int fi= 17;
    int max=96;
    int i=1;
    int rez=0;
    while(i<max) 
    {
        if((i*max)%fi==1) rez=i;
         i++;
    }
    System.out.println(rez);

The result is always 0.What is wrong?

Upvotes: 3

Views: 1769

Answers (2)

Carlo
Carlo

Reputation: 1579

I launched your program modified using max instead of rand as you wrote and adding some printf inside loop. Here's the code:

#include <stdio.h>

void main()
{
    int fi= 17;
    int max=96;
    int i=0;
    int rez=0;
    while(i<max) 
    {
        printf("\n%i", (i*max)%fi);

        if((i*max)%fi==1)
        {
            rez=i;
            printf(" -> %i", rez);
        }
         i++;
    }

    printf("\n");
    printf("\nFinal result: %i", rez);
    printf("\n");
}

And here's the output:

0
11
5
16
10
4
15
9
3
14
8
2
13
7
1 -> 14
12
6
0
11
5
16
10
4
15
9
3
14
8
2
13
7
1 -> 31
12
6
0
11
5
16
10
4
15
9
3
14
8
2
13
7
1 -> 48
12
6
0
11
5
16
10
4
15
9
3
14
8
2
13
7
1 -> 65
12
6
0
11
5
16
10
4
15
9
3
14
8
2
13
7
1 -> 82
12
6
0
11
5
16
10
4
15
9
3
14
8

Final result: 82

I don't get always 0 as you say. Where do you get 0?

Upvotes: 0

Harshit Singhvi
Harshit Singhvi

Reputation: 104

    import java.util.*;
 class hello
{
  public static void main (String[] args) throws java.lang.Exception
  {
    Random r=new Random();
    int i=1;
    while(i<96)
    {

      if(((i*96)%17)==1)
      { 
        System.out.println("i:- "+i);
     }
     i++;
   }
 }
}

Output: i:- 14 i:- 31 i:- 48 i:- 65 i:- 82

Upvotes: 1

Related Questions