> [!NOTE] Examiners' Advice > > Don't code more than the question asks (Section B/D) > > We encourage students to consider the Section B question and work out what the design marks are awarded for in that question - even if they struggle to code it formally it can help gain marks Section B questions tend to recycle the same ideas. Here are some useful code snippets. Learn and understand them! # Numeric Problems ## Modulo Operator ```java int x = 7 x % 3 = 1 x / 2 = 3 Use % to test for odd and even numbers x % 2 == 0 test for even x % 2 == 1 test for odd ``` # Test for Prime Numbers Note this is a very crude way of testing. Read [[Optimize Finding Prime Numbers]] for more on how to optimise this algorithm ```java boolean isPrime(int num) { boolean isPrime = true; for (int i = 2; i < num; i++) { if (num % i == 0) { isPrime = false; } } return isPrime; } ``` ## Random Numbers To find a random number between 1 and 100, you'd need to do something like this: ```Java double num = Math.random()*100; int ran = (int)num+1; System.out.println(ran); ``` You could also use the Random class as follows. ```java Random random = new Random(); int x = random.nextInt(100) + 1; System.out.println(x); ``` The following code prints out the numbers -1, 0, 1 randomly. This is really useful for making a monster walk randomly in a 2D game. ```java Random random = new Random(); int x = random.nextInt(3) - 1; System.out.println(x); ``` ## Finding the Sum of Digits Numerically ```java int digitSum2(int number) { int sum = 0; while(number > 0) { int remainder = number % 10; number = number / 10; sum += remainder; } return sum; } ``` # Strings and Chars ## Remember ```java char c = 'c' // single quotes String s = "Hello" // double quotes ```` ## This Idea is More Useful than You Might Think ```java for (int i= 0; i<26; i++) { System.out.println(Character.toString(i + 65)); } ``` ## Convert String to Char Array ```java // Basic way String s = "hello"; char [] c = new char[s.length]; for (int i = 0; i<s.length; i++){ c[i] = s.charAt(i); } // Easy way String s = "hello"; char [] c = s.toCharArray(); ``` ## Using Strings to Convert Hex to Denary ```java int HextoDenary(String val){ int num = 0; String hexVals = "0123456789ABCDEF"; for (int i = 0; i < val.length(); i++) { char c = val.charAt(i); int d = hexVals.indexOf(c); num = 16*num + d; } return num; } ``` ## Digit Sums Using Strings ```java int digitSum(int number){ int sum = 0; String num = Integer.toString(number); String [] digits = num.split(""); for (String character: digits) { sum += Integer.parseInt(character); } return sum; } ```