I am only given one hour to code this. [NOTE : NO arrays, pointers, recursion an
ID: 3887661 • Letter: I
Question
I am only given one hour to code this.
[NOTE : NO arrays, pointers, recursion and strings should be used in this code.]
1) How do I go about doing this is under an hour? Please include some thought processes.
2) What's the best way to savage the maximum amount of marks if I don't complete this in under an hour?
Explanation / Answer
1.) If u want to do this in an hour, first think about how to achieve the logic for happy number with single integer. After achieving this you can improve the logic for a range then u can improve the achieved logic to second range as well.
2.) I feel the good way is atleast achieving of whether given number is happy number or not. Better way is to find the number of happy numbers in given range and finally the best way is to achieve the logic for given question.
Please understand the below logic for more info :
#include<stdio.h>
#include <stdbool.h>
int digitSquareSum(int n) {
int squareSum = 0;
while (n){
squareSum += (n % 10) * (n % 10);
n /= 10;
}
return squareSum;
}
// method return true if n is Happy number
bool isHappynumber(int n) {
int slow, fast;
// initialize slow and fast by n
slow = fast = n;
do
{
// move slow number by one iteration
slow = digitSquareSum(slow);
// move fast number by two iteration
fast = digitSquareSum(digitSquareSum(fast));
}
while (slow != fast);
// if both number meet at 1, then return true
return (slow == 1);
}
// main code to test above methods
int main() {
int range1_1, range1_2, range2_1, range2_2;
printf("Enter 1st range: ");
scanf("%d %d",&range1_1,&range1_2);
printf(" Enter 2st range: ");
scanf("%d %d",&range2_1,&range2_2);
int range1count = 0;
int range2count = 0;
int firstLimit = 0;
int secondLimit = 0;
for(int j=0;j<2;j++){
if(j==0){
firstLimit = range1_1;
secondLimit = range1_2;
}else {
firstLimit = range2_1;
secondLimit = range2_2;
}
for(int i=firstLimit;i<=secondLimit;i++){
int n = i;
if (isHappynumber(n)){
if(j==0){
range1count = range1count + 1;
}else{
range2count = range2count + 1;
}
}
}
}
printf(" The numbers of happy numbers in the two ranges are: %d %d",range1count,range2count);
if(range1count==range2count){
printf(" The numbers of happy numbers in the two ranges are the same.");
}else if(range1count>range2count){
printf(" There are more happy numbers in the first range");
}else {
printf(" There are more happy numbers in the second range");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.