Pseudo-random numbers/Middle-square method: Difference between revisions
Content added Content deleted
(New post) |
|||
Line 814: | Line 814: | ||
{{out}} |
{{out}} |
||
<pre>959861 333139 981593 524817 432883 387691</pre> |
<pre>959861 333139 981593 524817 432883 387691</pre> |
||
=={{header|Java}}== |
|||
<syntaxhighlight lang="java"> |
|||
public final class MiddleSquareTask { |
|||
public static void main(String[] aArgs) { |
|||
MiddleSquare random = new MiddleSquare(675248); |
|||
for ( int i = 0; i < 5; i++ ) { |
|||
System.out.println(random.nextInt()); |
|||
} |
|||
} |
|||
} |
|||
final class MiddleSquare { |
|||
public MiddleSquare(int aSeed) { |
|||
final int length = String.valueOf(aSeed).length(); |
|||
if ( length % 2 == 1 ) { |
|||
throw new IllegalArgumentException("Seed must have an even number of digits"); |
|||
} |
|||
state = aSeed; |
|||
divisor = (int) Math.pow(10, length / 2); |
|||
modulus = (int) Math.pow(10, length); |
|||
} |
|||
public int nextInt() { |
|||
state = ( ( state * state ) / divisor ) % modulus; |
|||
return (int) state; |
|||
} |
|||
private long state; |
|||
private final int divisor, modulus; |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
959861 |
|||
333139 |
|||
981593 |
|||
524817 |
|||
432883 |
|||
</pre> |
|||
=={{header|jq}}== |
=={{header|jq}}== |