Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

Prime number, Sum of all, even & odd digits of given number

Notes:

I. Check a given number is prime or not: [Starts at : 00min:00sec]
II. Compute sum of digits of a given number : [Starts at: 15min:07sec]
III. Display digits of a given number in revers order: [Starts at: 25min:15sec]
IV. Compute sum of even, odd and all digits of a given number : [Starts at: 26min:26:sec]

I. Check a given number is prime or not: [Starts at : 00min:00sec]
Prime number is a number which is only divisible by 1 and itself
Note:
if n divides by any number from 2 to n - 1,
then n is not prime

Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour {
void Start () {
// program to find a given number is prime or not
int num = 7;
bool isPrime = true;
for (int i = 2; i < num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime == true)
Debug.Log (num + " is prime");
else
Debug.Log (num + " is not prime");
}
}

II. Compute sum of digits of a given number : [Starts at: 15min:07sec]
Note:
num%10 = returns last digit of the number
num/10 = returns remaining digits

Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour {
void Start () {
// program to find sum of digits of a given number
int num = 1234;
int sum = 0, lastDigit = 0;
while (num != 0) {
lastDigit = num % 10; // get the last digit
sum = sum + lastDigit; // add the last digit to sum
num = num / 10; // get the remaining digits
}
Debug.Log (sum);
}
}

III. Display digits of a given number in revers order: [Starts at: 25min:15sec]
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
int num = 1234;
int lastDigit = 0;
while (num != 0) {
lastDigit = num % 10; // get the last digit
Debug.Log (lastDigit);
num = num / 10; // get the remaining digits
}
}
}

IV. Compute sum of even, odd and all digits of a given number : [Starts at: 26min:26:sec]
Example Code:
using UnityEngine;
public class LoopingStatements : MonoBehaviour
{
void Start ()
{
int num = 1234;
int lastDigit = 0;
int sum = 0, sumOfEven = 0, sumOfOdd = 0;
while (num != 0) {
lastDigit = num % 10; // get the last digit
if (lastDigit % 2 == 0) {
sumOfEven += lastDigit; // or sumOfEven = sumOfEven + lastDigit;
} else {
sumOfOdd += lastDigit; // or sumOfOdd = sumOfOdd + lastDigit;
}
sum += lastDigit; // or sum = sum + lastDigit;
num = num / 10; // get the remaining digits
} Debug.Log ("Sum of all digits=" + sum);
Debug.Log ("Sum of even digits=" + sumOfEven);
Debug.Log ("Sum of odd digits=" + sumOfOdd);
}
}